JAVA 面试题:替换文本文件里的制定字符串
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA 面试题:替换文本文件里的制定字符串相关的知识,希望对你有一定的参考价值。
package testJava;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
public class ReplaceString {
public static void main(String[] args) {
File file = new File("c:\\test.txt");
ArrayList<String> content = new ArrayList<String>();
try {
InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader read = new BufferedReader(in);
String line = null;
while ((line = read.readLine()) != null) {
line = line.replaceAll("OldString", "NewString");
content.add(line);
}
read.close();
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
BufferedWriter write = new BufferedWriter(out);
Iterator<String> cont = content.iterator();
while (cont.hasNext()) {
write.write(cont.next()+"\r\n");
}
write.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Completed!");
}
}
以上是关于JAVA 面试题:替换文本文件里的制定字符串的主要内容,如果未能解决你的问题,请参考以下文章