You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.6 KiB

import java.io.*;
public class Editor{
private String content; //文本文件的内容
private String filepath; //文本文件的路径
private String charsetName; //文本文件的字符编码
public Editor(String filepath,String charsetName){
this.filepath=filepath;
this.charsetName=charsetName;
}
//把文件中的内容输入到content属性中
public void load(){
try{
InputStream in1=new FileInputStream(filepath);
InputStreamReader in2=
new InputStreamReader(in1,charsetName);
BufferedReader in3=new BufferedReader(in2);
String data=null;
content="";
while((data=in3.readLine())!=null)
content+=data+"\n";
in3.close();
}catch(IOException e){}
}
//把content属性的内容输出到文件中
public void save(){
try{
OutputStream out1=new FileOutputStream(filepath);
OutputStreamWriter out2
=new OutputStreamWriter(out1,charsetName);
PrintWriter out3=new PrintWriter(out2,true);
out3.print(content);
out3.close();
}catch(IOException e){}
}
//获得文本内容
public String getContent(){
return content;
}
// 替换content属性中的特定字符串
public void replace(String oldStr,String newStr){
content=content.replace(oldStr,newStr);
}
public static void main(String args[]){
Editor editor=new Editor("D:\\mydir\\data.txt","UTF-8");
editor.load(); //加载data.txt文件
editor.replace("Hello","Hi"); //替换特定字符串
editor.save(); //保存文件
}
}