将 csv 值提取到键值对中

Extract csv values into key value pairs

我有一个包含两列的 CSV 文件; A 列和 B 列。我想提取 ColumnA 和 ColumnB 的两个值,以便稍后在 for 循环中解析它们。

CSV 示例:

John, John Smith
James, James Bond

当我对变量 oldName 进行系统打印时,我的程序成功提取了 ColumnA。但是,我不知道如何提取 ColumnB 的值,我认为原因是我选择的数据结构,我不知道如何正确适应我的需要?

基本上,我希望我的 for 循环在第一次迭代中使用变量 oldName = "John" 和 newName = "John Smith",在第二次迭代中使用 oldName = "James" 和 newName = "James Bond" 等.

String fName = "TestFile.csv";
String thisLine; 
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
String oldName;
String newName;
int i=0; 

String[] GroupArray = new String[1000]; 
while ((thisLine = myInput.readLine()) != null)
{
    String strar[] = thisLine.split(",");
    
for(int j=0;j<strar.length;j++)
{
if(i!=0)
{
GroupArray[i] = strar[j];
}
else
{
GroupArray[i] = strar[j];
}
} 
i++;
} 
   try{ 
    for (int l = 0; l < i; l++)
    {
        oldName = GroupArray[0];
        newName = GroupArray[1];
        out.println ("User: "+ oldName +" has been renamed to: "+ newName +"<BR>");

你走在正确的轨道上,但你有一些多余的代码。请注意 DataInputStream#readLine 已弃用,因此我使用了 BufferedReader#readLine.

String filename = "/path/to/your/file";
File csv = new File(filename);
BufferedReader reader = new BufferedReader(new FileReader(csv));

String[] groupArray = new String[1000];

String line;
int i = 0;
while((line = reader.readLine()) != null) {
    String[] split = line.split(",");
    
    groupArray[i] = split[0].trim();
    groupArray[i+1] = (split.length > 1) ? split[1].trim() : "";
    
    i += 2;
}

String oldName, newName;
for(int j = 0; j < i; j += 2) {
    oldName = groupArray[j];
    newName = groupArray[j+1];
    System.out.println ("User: "+ oldName +" has been renamed to: "+ newName +"<BR>");
}

输入:

John, John Smith
James, James Bond

输出:

User: John has been renamed to: John Smith<BR>
User: James has been renamed to: James Bond<BR>

我认为您不必要地使任务过于复杂。以下示例应作为起点:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IOException {
        File file = new File("TestFile.csv");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String line;
        List<String[]> allLines = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            String[] splited = line.split("\s*,\s*");
            allLines.add(splited);                
        }
        
        for(String[] row : allLines){
            String oldName = row[0];
            String newName = row[1];
            System.out.println ("User: "+ oldName +" has been renamed to: "+ newName );
        }
    }
}