gpt4 book ai didi

java - 如何在 Java 中更新文件内容

转载 作者:行者123 更新时间:2023-11-29 05:20:51 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com