遇到此代码,它替换了给定值的所有字符。
File temp = File.createTempFile("newfile", ".txt");
FileWriter fw = new FileWriter(temp);
Reader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
while (br.ready()) {
fw.write(br.readLine().replaceAll("n", "j") + "\n");
}
fw.close();
br.close();
reader.close();
temp.renameTo(file);
}
而不是用“j”替换所有' s是不是有办法指定我想要更改的索引?
答案 0 :(得分:0)
答案 1 :(得分:0)
while语句中的行如下:
fw.write(br.readLine().replaceAll("n", "j") + "\n");
这可以扩展为:
String str = br.readLine(); //get text
String replace = str.replaceAll("n", "j"); //replace content
replace = replace + "\n"; //add new line
fw.write(replace); //write to file
对于替换某个索引的实例,您可能希望执行类似的操作:
StringBuilder str = new StringBuilder(br.readLine()); //Read line into StringBuilder
if(str.length() > 3) //Check if string is long enough
str.setChar(4, 'x'); //Replace character in line at index 4 to 'x'
fw.write(str); //write to file