gpt4 book ai didi

Java - 加载文件,替换字符串,保存

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

我有一个程序从用户文件中加载行,然后选择字符串的最后一部分(这将是一个 int)

这是它保存的样式:

nameOfValue = 0
nameOfValue2 = 0

等等。我已经确定地选择了这个值——我通过打印来调试它。我似乎无法将其保存回去。

if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}

我该如何重新保存它?我试过 bufferedwriter,但它只会删除文件中的所有内容。

最佳答案

我的建议是,保存原始文件的所有内容(在内存中或在临时文件中;我会在内存中进行),然后重新写入,包括修改。我相信这会奏效:

public static void replaceSelected(File file, String type) throws IOException {

// we need to store all the lines
List<String> lines = new ArrayList<String>();

// first, read the file and store the changes
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
if (line.startsWith(type)) {
String sValue = line.substring(line.indexOf('=')+1).trim();
int nValue = Integer.parseInt(sValue);
line = type + " = " + (nValue+1);
}
lines.add(line);
line = in.readLine();
}
in.close();

// now, write the file again with the changes
PrintWriter out = new PrintWriter(file);
for (String l : lines)
out.println(l);
out.close();

}

然后您将像这样调用该方法,提供您要修改的文件和您要选择的值的名称:

replaceSelected(new File("test.txt"), "nameOfValue2");

关于Java - 加载文件,替换字符串,保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8032223/

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