Java 中对于文本文档的操作除了之前介绍的字节流操作外,一般对于文本数据使用FileReader与FileWriter进行操作,要高效一些。这一组方法是直接对字符进行操作。具体实例如下:
1 使用FileReader读文件(这里面有中文的时候,有些时候会有乱码出现,关于此问题,在后面的文章里会有涉及,自己也可以以思考办法解决)
public void testFileReader() {
File file=new File("D:\\test.txt");
FileReader fr=null;
try {
fr=new FileReader(file);
char[] c=new char[24];//每次都24个(注意这里应该为偶数,因为一个汉字是两个字符)
int len;
while((len=fr.read(c))!=-1) {
String str=new String(c,0,len);
System.out.println(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
2 使用FileWriter进行写文件
public void testFileWriter() {
File file=new File("D:\\test1.txt");
FileWriter fr=null;
try {
fr=new FileWriter(file);
fr.write(new String("asdas 啊但是发射点 asdfd 123"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3 FileReader 与 FileWriter 结合使用构造方法
public void copyDoc(String src,String dst) {
FileReader fr=null;
FileWriter fw=null;
try {
File file1=new File(src);
File file2=new File(dst);
fr=new FileReader(file1);
fw=new FileWriter(file2);
char[] c=new char[100];
int len;
while((len=fr.read(c))!=-1) {
fw.write(c, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fw!=null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
希望对大家有帮助!!