2010-11-10 30 views
1

我如何讀取現有的文本文件,然後修改一樣,如果我得到這樣如何基於某些條件下讀取和修改的文本文件

一些文本蘋果1 3 5

一定條件下它的一些價值

現在,每當我得到一個整數值時,我必須將它的計數增加1並再次保存到同一個文件中。

例如,如果我讀像上面我應該能夠節省

蘋果2 4 6

回到同一文件中的一些內容再次

我的代碼看起來像

嘗試FileWriter fstream = new FileWriter(「c:\ Apple.txt」,true);

 FileReader inputFileReader = new FileReader("c:\\Apple.txt"); 
     BufferedReader inputStream = new BufferedReader(inputFileReader); 
     PrintWriter outputStream = new PrintWriter(fstream); 



     while((inline=inputStream.readLine())!=null) 
     { 
      values=inline.split("-"); 

      Integer l = Integer.parseInt(values[2])+1; 
      outputStream.print((inline.replaceAll(values[2],l.toString()))); 

     } 

     outputStream.close(); 


    } 

所以,我得到這樣

蘋果的輸出1 3 5蘋果1 4 5

但我需要的輸出是

蘋果1 4 5

在advace謝謝

+0

你是否自己寫過任何代碼?顯示你卡在哪裏,我們可以幫助 – JoseK 2010-11-10 13:21:12

+0

刪除你的意見,並附上你的代碼的問題 – 2010-11-10 14:42:40

+0

@Jose K我已更新我的問題 – Ankita 2010-11-10 15:03:41

回答

0

你不能在同一個文件上交互地做它(或者至少也許你可以b UT斯達康這將是非常棘手的)..你可以

  • 打開輸入文件
  • 文件
    • 打開輸出文件
    • 每條線路檢查您的病情,如果是真的
      • 根據您要修改的內容生成新行
      • 將其保存在輸出文件上
    • 如果假
      • 複製行成新的文件,而無需修改它
  • 接近這兩個文件
  • 刪除第一個,首先重命名第二個到(你可以很容易地用API做功能)
1

將代碼拆分爲不同的方法調用:

File f = getFile(); 
String text = getFileContents(f); 
if(matchesRequirements(text)){ 
    String newText = performReplacements(text); 
    writeFile(newText, f); 
} 

現在,您可以實現這些方法:

private static void writeFile(String newText, File f){ 
    // TODO implement this method 
} 

private static String performReplacements(String text){ 
    // TODO implement this method 
    return null; 
} 

private static boolean matchesRequirements(String text){ 
    // TODO implement this method 
    return false; 
} 

private static String getFileContents(File f){ 
    // TODO implement this method 
    return null; 
} 

private static File getFile(){ 
    // TODO implement this method 
    return null; 
} 

看多遠你,問你哪裏有問題,具體的問題。

0

我用RandomAccessFile,它工作正常。

相關問題