Java 用replacingAll()提问
我想将文件中Java 用replacingAll()提问,java,Java,我想将文件中[FileName]的所有符号替换为。任何想法和线索都会来的。我是初学者,请对我耐心点 这是我的密码: public class TextFormatter { public static void main(String[] args) { // TODO Auto-generated method stub TextFormatter tf = new TextFormatter(); File f = new File
[FileName]
的所有符号替换为
。任何想法和线索都会来的。我是初学者,请对我耐心点
这是我的密码:
public class TextFormatter {
public static void main(String[] args) {
// TODO Auto-generated method stub
TextFormatter tf = new TextFormatter();
File f = new File("D:\\Temp.txt");
try {
tf.replaceInFile(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void replaceInFile(File file) throws IOException {
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
fw.write(br.readLine().replace("[", "<"));
fw.write(br.readLine().replace("]", ">"));
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
}
}
第36行是
fw.write(br.readLine().replace("]", ">"));
第19行是
tf.replaceInFile(f);
br.readLine()
每次调用一行时都会读取该行。因此,如果要在同一行中替换[
和]
,则不应调用readLine()
两次(也不应调用fw.write()
两次)
而且ready()
不是您应该使用的。只需读取每一行,直到readLine()
返回空值:
String line;
while((line = br.readLine()) != null) {
line = line.replace("[", "<");
line = line.replace("]", ">");
fw.write(line);
}
字符串行;
而((line=br.readLine())!=null){
行=行。替换(“[”,”);
fw.写入(行);
}
另外,我想您希望保留行分隔符。因此,您应该将FileWriter包装到PrintWriter中,并使用println()
最后,您应该确保关闭读写器,不管方法中发生了什么。使用语句。根据JavaDoc,此函数返回
包含行内容的字符串,不包括任何行终止字符,如果已到达流的结尾,则为null
因此,您应该检查对br.readLine()
的每个调用,以确保它不是null
,然后再尝试对其执行操作…例如
fw.write(br.readLine().replace("]", ">"));
^ ^
This is null..so attempting this throws a `NullPointerException`
但更大的问题是,当您打算在同一行上进行第二次替换时,您错误地阅读了新行。将其更改为此可解决这两个问题:
String line = br.readLine();
if(line != null) {
fw.write(line.replace("[", "<"));
fw.write(line.replace("]", ">"));
}
stringline=br.readLine();
如果(行!=null){
fw.write(第行替换(“[”,”);
}
String line = br.readLine();
if(line != null) {
fw.write(line.replace("[", "<"));
fw.write(line.replace("]", ">"));
}