2010-01-01 83 views
0

我需要檢索並更改將位於第一行的文本文件中的數字。它會改變長度,例如「4」,「120」,「78」來表示文本文件中保存的數據條目。正在檢索和替換文本文件中的數字

+1

當其他人爲你做他們的作業總是更好。 還是我完全錯了,這是現實生活中的生產問題? – 2010-01-01 23:38:26

+0

我想換個話題。它姿勢不佳。你能否添加一些更多的細節? – duffymo 2010-01-01 23:38:34

回答

4

如果您需要更改第一行的長度,那麼您將不得不讀取整個文件並重新寫入。我建議先寫入一個新文件,然後在確定寫入文件正確後重新命名該文件,以避免程序在操作中途崩潰時丟失數據。

2

這將從MyTextFile.txt中讀取,並抓住第一個數字改變它,然後將該新數字和文件的其餘部分寫入臨時文件。然後它將刪除原始文件並將臨時文件重命名爲原始文件的名稱(在本例中爲MyTextFile.txt)。我不確定這個數字到底應該改變到什麼程度,所以我隨意創建了它。如果你解釋一下這個文件包含的數據條目,我可以幫助你更多。無論如何,希望這會幫助你。

import java.util.Scanner; 
import java.io.*; 

public class ModifyFile { 
    public static void main(String args[]) throws Exception { 
     File input = new File("MyTextFile.txt"); 
     File temp = new File("temp.txt"); 
     Scanner sc = new Scanner(input); //Reads from input 
     PrintWriter pw = new PrintWriter(temp); //Writes to temp file 

     //Grab and change the int 
     int i = sc.nextInt(); 
     i = 42; 

     //Print the int and the rest of the orginal file into the temp 
     pw.print(i); 
     while(sc.hasNextLine()) 
      pw.println(sc.nextLine()); 

     sc.close(); 
     pw.close(); 

     //Delete orginal file and rename the temp to the orginal file name 
     input.delete(); 
     temp.renameTo(input); 
    } 
} 
相關問題