2013-04-04 59 views
-2

嗨,我試圖讀取一個文本文件,然後將讀取的數據寫入Java中的新文件,方法是更改​​從第一個文件。我卡在這裏:我可以讀取文件,但選擇性修改非常困難,我無法理解如何修改文件中某一行的特定部分?該文本文件是details.txt,並對其內容的,如:如何通過讀取另一個文件並對其進行一些更改來寫入文件

彼得,紐約,2331.32

沃爾什,加利福尼亞州,3224.43

等。現在,我想修改與陣列包含更新值的雙重價值類似以下內容:

Double[] updatedValues = {33231.23,32344.34}; 

誰能告訴我如何通過讀取數組中的值,並寫入這些值到一個新的,更新的雙重價值文本文件?

回答

2

一種可能的方法是使用String.split()方法拆分行,撰寫新行並將其寫入文件。例如:

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

嘗試

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長度應爲> =文件中的行數

0

可以使用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 
} 
相關問題