如何通过读取另一个文件并对其进行一些更改来写入文件

问题描述:

嗨,我试图读取一个文本文件,然后将读取的数据写入Java中的新文件,方法是更改​​从第一个文件。我卡在这里:我可以读取文件,但选择性修改非常困难,我无法理解如何修改文件中某一行的特定部分?该文本文件是details.txt,并对其内容的,如:如何通过读取另一个文件并对其进行一些更改来写入文件

彼得,纽约,2331.32

沃尔什,加利福尼亚州,3224.43

等。现在,我想修改与阵列包含更新值的双重价值类似以下内容:

Double[] updatedValues = {33231.23,32344.34}; 

谁能告诉我如何通过读取数组中的值,并写入这些值到一个新的,更新的双重价值文本文件?

一种可能的方法是使用String.split()方法拆分行,撰写新行并将其写入文件。例如:

String[] data = line.split(","); 
data[2] = "" + updatedValues[i]; 
// now join array of data back and write it to the new file. 

尝试

double[] updatedValues = {33231.23,32344.34 ..... 
    Scanner sc = new Scanner(new File("file1")); 
    PrintWriter pw = new PrintWriter(new File("file2")); 
    for (int i = 0; sc.hasNextLine(); i++) { 
     String l = sc.nextLine(); 
     l = l.substring(0, l.lastIndexOf(',')); 
     pw.printf("%s,%f%n", l, updatedValues[i]); 
    } 
    sc.close(); 
    pw.close(); 

注意updatedValues长度应为> =文件中的行数

可以使用String.split()做到这一点

这里是Pseduocode:

Double[] updatedValues = {33231.23,32344.34} 
While (read line from file !=null or empty) 
{ 
String[] tokens= line.split(","); 
tokens[2] = "" + updatedValues[i]; 
//now write the three values in the string array tokens to another file separated by some seperator 
}