JAVA字节流与字符流总结

35 篇文章 0 订阅

字节流:

字节流是处理的基本单位是单个的字节,在java中有两个最基本的抽象字节流类。

InputStreamOutputStream 均为抽象类

在InputStream中有一个最基本的方法,从字节流中读取一个字节,若到了流的末尾则返回-1,用这个方法每读一个字符就会进行一次系统读取请求,效率较低。另一个重载的方法可以读取多个字节,但在底层仍然是调用的read()方法

public abstract int read() throws IOException
public abstract int read(byte[]) throws IOException 

使用方法

在Java中有些Stream能从文件或者其他地方获取字节,另一些Stream虽然不具备这一功能,但是却能把字节变为更有用的格式,例如:

FileInputStream fin = new FileInputStream("employee.dat");
DataInputStream din = new DataInputStream(fin);
double s = din.readDouble();

字符流:

在Java中字符流的基本单位是Unicode码元(2字节)。
输出字符流OutputStreamWriter:把要写入文件的字符序列(Unicode)转换为指定编码方式下的字节序列,然后写入文件中,其中指定编码为本地系统的编码。
出入字符流InputStreamReader:把要读取的字节序列按指定方式解码为Unicode存入内存中。
例如:

InputStreamReader in = new InputStreamReader(System.in);
InputStreamReader in = new InputStreamReader(new FileInputStream("kremlin.dat", "ISO8859_5"));

使用方法:

写字符

PrintWriter out = new PrintWriter(new FileWriter("employee.txt"));
String name = "China!";
out.println(name);

根据运行系统的不同,println 会添加不同的end-of-line(Windows:”\r\n”,UNIX:”\n”),可以通过System.getProperty("line.separator")得到。

读字符

在Java1.5之前,唯一的方法就是使用BufferedReader,在新的版本中可以使用功能强大的Scanner

BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("employee.txt"), "UTF-8"));
String line;
while ((line = in.readLine()) != null) { 
    do something
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值