听着张孝祥老师关于缓冲区知识的课,发现还是有一些没有掌握,动手试了一下,果然发现了问题。
先讲一下关于java缓冲区的知识,应用程序和IO设备之间存在一个缓冲区,一般流是没有缓冲区的,但是如果存在缓冲区,就会发现很大的问题。
错误代码如下:为了确保问题发生,我使用了BufferedOutputStream,使得手动构造出了一个缓冲区。
- import java.io.*;
- public class Test {
- public static void main(String[] args) throws Exception{
- DataOutputStream out = new DataOutputStream(
- new BufferedOutputStream(
- new FileOutputStream("1.txt")));
- out.writeChars("hello");
- FileInputStream in = new FileInputStream("1.txt");
- int len = in.available();
- byte[] b = new byte[len];
- int actlen = in.read(b);
- String str = new String(b);
- System.out.println(str);
-
- }
- }
|
发现什么问题了吗?
因为如果没有缓冲区,应用程序每次IO都要和设备进行通信,效率很低,因此缓冲区为了提高效率,当写入设备时,先写入缓冲区,等到缓冲区有足够多的数据时,就整体写入设备。这就是问题所在,上个例子中,当我们写入hello时,由于hello占用空间很小,所以暂时存放在缓冲区中,后来输入流想要从文件中读取,但是由于文件中没有字节,所以不能读取hello。
这里,解决方法很简单,只要调用out.flush() 或者out.close()即可,这是把缓冲区的数据手动写入文件。
正确代码如下:
- import java.io.*;
- public class Test {
- public static void main(String[] args) throws Exception{
- DataOutputStream out = new DataOutputStream(
- new BufferedOutputStream(
- new FileOutputStream("1.txt")));
- out.writeChars("hello");
- out.close();
- FileInputStream in = new FileInputStream("1.txt");
- int len = in.available();
- byte[] b = new byte[len];
- int actlen = in.read(b);
- String str = new String(b);
- System.out.println(str);
-
- }
- }
|