如何使用Java更新文件内容

时间:2014-07-18 21:09:08

标签: java

首先,我输出文件的内容,这是我的代码。然后,我将做一些字符串工作来编辑每一行。如果我保存更改怎么办,该怎么办?我可以不创建tmp文件吗?

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 is@@@@@@@@@@@@@@@@@@@@@@@@"+s)
    // do something to edit each line and update the file
  }        
} catch (IOException e) {
  logger.fatal(e);
}

2 个答案:

答案 0 :(得分:3)

以下步骤可以实现您的目标。

  • 实例化FileWriter对象以创建tmp文件。

     FileWriter fw = new FileWriter("tmp");
    
  • 从源文件中逐行阅读。

  • 在内存中修改此行(字符串对象)。

  • 在tmp文件中写出此字符串。

      fw.write(line);
    
  • 关闭文件句柄。

  • 将tmp文件重命名为源文件名。

     sourceFile.renameTo(targetFile);
    

答案 1 :(得分: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");    
}