字符流分为两种:Reader(字符输入流)、Writer(字符输出流)
Reader是一个抽象类,要进行文件读取,使用子类FileReader;
Writer是一个抽象类,要将数据输入到文件中,使用子类FileWrite;
Reader的**read()**方法:
public static void main(String[] args) {
File infile = new File("D:/test/input.txt");
File outfile = new File("D:/test/output.txt");
Reader reader=null;
Writer writer=null;
try {
reader=new FileReader(infile);
writer=new FileWriter(outfile);
int value=-1;
while ((value=reader.read())!=-1){
writer.write(value);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
/*如果不关闭流的话,则数据无法写入到文件中,数据就有可能保存在缓存中并没有输出到目标源*/
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(writer!=null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Reader的**read(char[ ] b)**方法:
public static void main(String[] args) {
File infile = new File("D:/test/input.txt");
Reader reader=null;
try {
reader=new FileReader(infile);
int len=-1;
char[] chars=new char[3];
while((len=reader.read(chars))!=-1){ //同样的将从文件中读取的数据存放在数组中,
System.out.println(chars);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Writer的write()方法:
Writer的write(char[ ] b)方法:
Writer类还提供了一个直接输出字符串的方法:write(String str):
public static void main(String[] args) {
File file=new File("D:/test/output.txt");
Writer writer=null;
try {
writer=new FileWriter(file);
/*输出字节流的write方法可以写new char[],String,int*/
writer.write(1);//int型
writer.write("hello");//String型
writer.write(new char[]{'a','b','c'});//字符数组
writer.write("world",1,3);//带有长度的输出,范围是world的[1,3)范围内的字符
} catch (IOException e) {
e.printStackTrace();
}finally { /*特别注意的是,如果不关闭数据流的话,则数据写不到文件中,数据就有可能保存在缓存中并没有输出到目标源*/
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
但是Reader没有提供读取字符串的方法,只能通过读取字符来实现字符串的读取了;
如果字符流不关闭,数据就有可能保存在缓存中无法输出到目标源。这种情况下就必须强制刷新flush才能够得到完整数据:
public static void main(String[] args) {
File file=new File("D:/test/output.txt");
Writer writer=null;
try {
writer=new FileWriter(file);
/*输出字节流的write方法可以写new char[],String,int*/
writer.write(new char[]{'a','b','c','d','e'},1,2);
writer.write("world",1,3);
/*如果不关闭数据流,则需要强制刷新,将缓存区的数据输出到目标文件,否则就无法将数据写到文件中*/
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Reader类同样继承了Closeable接口,Closeable继承了AutoCloseable;Writer类继承了AutoCloseable接口;
所以它们也可以通过将创建对象的过程写在try()的括号中,实现自动关闭字符流。
字符流(Reader、Writer)适合处理中文,字节流(InputStream、OutputStream)适合处理一切数据类型,所以通常使用字节流