Java - 加载文件,替换字符串,保存 [英] Java - Load file, replace string, save
问题描述
我有一个程序从用户文件加载行,然后选择字符串的最后部分(这将是一个int)
这是它保存的样式in:
nameOfValue = 0
nameOfValue2 = 0
等等。我已经确定了值 - 我通过打印进行调试。
if(nameOfValue.equals(type)){
System.out.println(nameOfValue +等于+ type);
value.replace(value,Integer.toString(Integer.parseInt(value)+1));
}
如何重新保存它?我已经尝试了bufferedwriter,但它只是擦除文件中的所有内容。 我的建议是,保存原始的所有内容文件(无论是在内存中还是在临时文件中,我都会在内存中执行),然后重新写入,包括修改。我相信这会工作:
$ b $ pre $ public static void replaceSelected(File file,String type)throws IOException {
//我们需要存储所有的行
List< String> lines = new ArrayList< String>();
//首先读取文件并保存更改
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();
//现在,再次使用变化写入文件
PrintWriter out = new PrintWriter(file);
for(String l:lines)
out.println(l);
out.close();
你可以调用这个方法,要修改的文件和要选择的值的名称:
replaceSelected(new File(test.txt ),nameOfValue2);
I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)
Here's the style it's saved in:
nameOfValue = 0
nameOfValue2 = 0
and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.
if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}
How would I resave it? I've tried bufferedwriter but it just erases everything in the file.
My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:
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();
}
And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:
replaceSelected(new File("test.txt"), "nameOfValue2");
这篇关于Java - 加载文件,替换字符串,保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!