Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字节流与字符流 #26

Open
SillyBoy007 opened this issue Mar 25, 2018 · 0 comments
Open

字节流与字符流 #26

SillyBoy007 opened this issue Mar 25, 2018 · 0 comments

Comments

@SillyBoy007
Copy link
Owner

以文件操作为例,输入和输出操作为:
1.定义一个File类
2.通过字节流或字符流的子类对象为父类对象实例化
3.进行数据的读(输入)或写(输出)
4.资源操作关闭

一.字节流

1.字节输出流OutputStream(important)
OutputStream实现了Closeable,Flushable两个接口:
OutputStream提供三个输出方法:
1.输出单个字节:public abstract void write(byte b) throws IOException
2.输出全部字节数组:public void write(byte[] b) throws IOException
3.输出部分字节数组;public void write(byte[] b,int off , int len) throws IOException
OutputStream子类方法:
创建或覆盖已有文件:public FileOutputStream(File file)
文件内容追加:public FileOutputStream(File file,boolean append)
2.字节输入流InputStream
InputStream实现了Closeable接口。
InputStream读取方法:
1.读取单个字节:public abstract int read() thros IOException
while循环,返回每次读取的字节数据或者-1(没有数据)
2.将读取的数据保存在字节数组里:public int read (byte[] b) throws IOException
返回读取的数据长度,读取到结尾返回-1
3.将读取的数据保存在部分字节数组里:public int read (byte[] b,int off,int len) throws IOException
返回部分数据的长度,若读取到结尾返回-1

二.字符流

1.字符输出流Writer
实现了Appendable,Closeable,Flushable接口
Writer类定义了如下方法:
1.输出全部字符数组:public void write(char [] cbuf) throws IOException
2.输出字符串:public void write (String str) throws IOException
字符流可以输出字符串.

2.字符输入流Reader
实现了Readable,Closeable接口
Reader类定义了如下方法:
1.读取内容到字符数组

字节流与字符流的区别
1.字节流直接与终端进行交互,字符流需要经过数据缓冲区进行交互
2.OutputStream即使没有关闭也能输出,而在Writer不能输出数据,可以使用flush()强制清空缓冲区
3.字符流最大的优点是可以对中文字符的有效处理
4.处理中文优先字符流,没有中文使用字节流
5.字符流的子类有转换流,磁盘上都是对字节的操作

转换流
InputStreamReader:Reader的子类
OutputStramWriter:Writer的子类

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant