首页 > 代码库 > JAVA 面试题:替换文本文件里的制定字符串
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 面试题:替换文本文件里的制定字符串
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。