首先,我输出文件的内容,这是我的代码。然后,我将做一些字符串工作来编辑每一行。如果我要保存更改怎么办?我可以在不创建 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);
}
最佳答案
以下步骤可以实现您正在寻找的内容。
实例化 FileWriter 对象以创建 tmp 文件。
FileWriter fw = new FileWriter("tmp");
从源文件中逐行读取。
修改内存中的这一行(字符串对象)。
在 tmp 文件中写出该字符串。
fw.write(line);
关闭文件句柄。
将 tmp 文件重命名为源文件名。
sourceFile.renameTo(targetFile);
关于java - 如何用Java更新文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24833846/