前面介绍的文件字节流可以处理所有的文件,但是字节流不能很好的处理Unicode字符,经常会出现“乱码”现象。所以,我们处理文本文件,一般可以使用文件字符流,它以字符为单位进行操作。
【示例】
import java.io.*;
public class TestReader {
public static void main(String[] args) {
File file =new File("abc.txt");
Reader reader=null;
try {
reader= reader = new FileReader(file);
char[] flash=new char[1024];
int len=-1;
while((len=reader.read(flash))!=-1){
String str=new String(flash,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
try {
if(null!=reader)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【示例】
public class TestWriter {
public static void main(String[] args) {
File file=new File("ac.txt");
Writer writer=null;
try {
writer=new FileWriter(file);
//写法一
// String str="xue xi java 坚持";
// char[] chars=str.toCharArray();
// writer.write(chars,0,chars.length);
//写法二
// String str="xue xi java 坚持\n写法二";
// writer.write(str);
//写法三
writer.append("xue xi java 坚持").append("\n写法三");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null!=writer)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【示例】使用FileReader与FileWriter实现文本文件的复制
import java.io.*;
public class TestCopyReadrWriter {
public static void main(String[] args) {
copy("abc.txt","ace.txt");
}
public static void copy(String srcPath,String destPath){
Reader reader=null;
Writer writer=null;
try {
reader=new FileReader(srcPath);
writer= new FileWriter(destPath);
char[] chars=new char[1024];
int len=-1;
while((len=reader.read(chars))!=-1){
writer.write(chars,0,chars.length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try {
if(null!=writer)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(null!=reader)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}