2017-09-27 42 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