字节流和字符流操作的本质区别只有一个:字节流是原生的操作,而字符流是经过处理后的操作。
在进行网络数据传输、磁盘数据保存所支持的数据类型只有字节。
字符输出流
字符更加适合去处理中文数据,Writer是字符输出流的处理类。这个类定义如下:
public abstract class Writer implements Appendable, Closeable, Flushable
与OutputStream类相比,多实现了一个Appendable
接口。
因为Writer也是一个抽象类,如果要操作文件,使用它的间接子类FileWriter
。
Writer类中也提供了许多write方法,这里简单列举几个:
- public void write(int c) throws IOException
- public void write(char cbuf[]) throws IOException
- public void write(String str) throws IOException
举例:使用Writer输出
public class TestStream {
public static void main(String[] args) {
String directory = "D:"+File.separator+"test1"+File.separator
+"java"+File.separator+"hh.txt";
//File和本地文件系统相关联
File file = new File(directory);
try (Writer writer = new FileWriter(file);){
writer.write(49); //字符的ASCCI
writer.write('\n');
writer.write("hello\n");
writer.write(new char[]{'a','b','c'});
writer.write("\n");
writer.write("生活如此艰辛!");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符输入流
字符输入流的处理类为Reader。Reader类的定义结构如下:
public abstract class Reader implements Readable, Closeable
Reader也是一个抽象类,如果要进行文件的读取,也要用到它的间接子类FileReader
。
Reader中也提供了一些方法,读取文件内容:
- public int read() throws IOException
- public int read(char cbuf[]) throws IOException
- abstract public int read(char cbuf[], int off, int len) throws IOException;
举例:使用Reader读取
public class TestStream {
public static void main(String[] args) {
String directory = "D:"+File.separator+"test1"+File.separator
+"java"+File.separator+"hh.txt";
//File和本地文件系统相关联
File file = new File(directory);
try (Reader reader = new FileReader(file);){
char[] buff = new char[1024];
int len = -1;
while ((len = reader.read(buff))!= -1){
System.out.println(new String(buff, 0, len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
简单总结:
1. 所有的字符都需要通过内存缓冲来进行处理。如果字符流不关闭,数据就有可能保存在缓存中并没有输出到目标源。这种情况下必须强制刷新。
2. 只有处理中文时会用到字符流,其他一般都使用字节流。