2014-07-18 25 views
0

首先,我輸出文件的內容,這裏是我的代碼。然後,我會做一些字符串工作來編輯每一行。如果我要保存更改,怎麼辦?我可以做到這一點,而無需創建一個tmp文件?如何更新Java中的文件內容

String executeThis = "cat" + " " + "/var/lib/iscsi/nodes/" 
    + iscsiInfo.selectedTargets2.get(i) + "/" + myString + "/default"; 
String inputThis = ""; 
Process process = ServerHelper.callProcessWithInput(executeThis, inputThis); 

try {   
    logger.debug("stdOutput for editing targets credential:"); 
    BufferedReader stdOutput = new BufferedReader(
    new InputStreamReader(process.getInputStream())); 

    String s = null;   
    while ((s = stdOutput.readLine()) != null) { 
    logger.info("The content [email protected]@@@@@@@@@@@@@@@@@@@@@@@"+s) 
    // do something to edit each line and update the file 
    }   
} catch (IOException e) { 
    logger.fatal(e); 
} 
+1

你爲什麼要執行一個進程而不是使用'FileReader'? – McLovin

+0

是的,你可以通過關閉正在進行文件更改的流來做到這一點! – Devavrata

+0

使用BufferedWriter http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html。我不會建議每次關閉並重新打開流。 – Kode

回答

2

以下步驟可以實現您正在查找的內容。

  • 實例化一個FileWriter對象來創建一個tmp文件。

    FileWriter fw = new FileWriter("tmp"); 
    
  • 從源文件逐行讀取。

  • 在內存中修改此行(字符串對象)。

  • 在tmp文件中寫出這個字符串。

    fw.write(line); 
    
  • 關閉文件句柄。

  • 將tmp文件重命名爲源文件名。

    sourceFile.renameTo(targetFile); 
    
+0

謝謝!如何逐行讀取原始文件。我無法在FileWriter –

+1

[BufferedWriter.readLine()](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine())中找到hasNextLine()相關的方法。你甚至嘗試過谷歌搜索嗎? – Tim

+0

感謝您的回答。但它是BufferedReader.readLine(),不在BufferedWriter –

0

這個問題已經回答了here。我重複這個答案。

public static void replaceSelected(String replaceWith, String type) { 
    try { 
     // input the file content to the String "input" 
     BufferedReader file = new BufferedReader(new FileReader("notes.txt")); 
     String line;String input = ""; 

     while ((line = file.readLine()) != null) input += line + '\n'; 

     System.out.println(input); // check that it's inputted right 

     // this if structure determines whether or not to replace "0" or "1" 
     if (Integer.parseInt(type) == 0) { 
      input = input.replace(replaceWith + "1", replaceWith + "0"); 
     } 
     else if (Integer.parseInt(type) == 1) { 
      input = input.replace(replaceWith + "0", replaceWith + "1"); 
     } 

     // check if the new input is right 
     System.out.println("----------------------------------" + '\n' + input); 

     // write the new String with the replaced line OVER the same file 
     FileOutputStream File = new FileOutputStream("notes.txt"); 
     File.write(input.getBytes()); 

    } catch (Exception e) { 
     System.out.println("Problem reading file."); 
    } 
} 

public static void main(String[] args) { 
    replaceSelected("Do the dishes","1");  
} 
+0

因爲這是OP所要求的並不意味着這是他應該做的。當他知道他將要編輯它們時,手術上重寫文件中的每一行都不是良好性能的配方,也不適合乾淨的程序設計。 – Tim

+0

我同意你的意見。這不是更好的解決方案,但它是一種解決方案。我只是回答他的問題。 但你的建議是絕對正確的! – Jimmysnn