2017-09-27 104 views
2

我有一个程序有一个2D数组,我需要写入一个CSV文件,但我只需要写一个数组的索引。我使用.get(0).set(4,newAmount)在第一个索引中设置一个值,但如果有意义的话,我需要将索引的所有值写入文件。写一个二维数组到一个csv文件

  fw = new FileWriter(FILE_NAME, true); 
     bw = new BufferedWriter(fw); 

     System.out.println("Enter the name of the person you want to change amount for"); 
     String changeName = FileUtility.getInput().nextLine(); 
     String newAmount; 



     Scanner s = new Scanner(new File(FILE_NAME)); 
     String str = ""; 
     List<List<String>> list = new ArrayList<List<String>>(); 

     while (s.hasNext()) { 
     list.add(Arrays.asList(s.nextLine().split(","))); 
} 

if (list.get(0).get(0).equalsIgnoreCase(changeName)) { 
    System.out.println("Enter the new amount paid for the player"); 
    newAmount = FileUtility.getInput().nextLine(); 
    list.get(0).set(4, newAmount); 
    //write to csv file here 

回答

0

将此代码放在代码的底部。

String csv = list.stream() 
    .map(row -> row.stream() 
     .map(col -> col.toString()) 
     .collect(Collectors.joining(", "))) 
    .collect(Collectors.joining("\n")); 
writer.write(csv); 
+0

是行不通的,它只是删除了存在 –

+0

@RyanBlanchard你的意思是扫描的文件具有空值的文件中的任何内容? – kangtaku

相关问题