Java学习笔记二十四(IO流之Buffered、Data InputStream和OutputStream类

BuffedInputStream和BufferedOutputStream类

这两个流都是高级流,内部维护了一个缓冲区(实际上就是一个字节数组,默认大小是8k),当缓冲区满时,将缓冲区的数据一次性写入,减少了io操作的次数,在一定程度上提高了效率。在读取较小的文件时,如果缓冲区未满而文件已结束,则调用flush()函数刷新写入文件,或者是调用close()函数关闭管道(在close函数内部调用了刷新缓冲区的操作)。

实现此高级流时需要先实现FileInputStream和FileOutpuStream类(低级流)。在关闭管道时,要先关闭高级流,再关闭低级流(如果流太多,只关高级流也可以,最好在实现高级流时将低级流在构造方法括号内new出来,即可以只关闭高级流)。

简单的输出实现:

public class TestBuffer {
	public static void main(String[] args) {
			FileOutputStream file = null;
			BufferedOutputStream  file1 = null;
		try {	
			file = new FileOutputStream("C:\\keshe\\b.txt");
			file1 = new BufferedOutputStream(file);
			file1.write(45);
			file1.flush();              
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				file1.close();
				file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

简单的输入实现:

public class TestBuffer1 {
	public static void main(String[] args) {
		FileInputStream file = null;
		BufferedInputStream  file1 = null;
	try {	
		file = new FileInputStream("C:\\keshe\\b.txt");
		file1 = new BufferedInputStream(file);
		System.out.println(file1.read());              
	} catch (IOException e) {
		e.printStackTrace();
	}finally {
		try {
			file1.close();
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

如果字节数组的大小大于缓冲区的大小,则会直接越过缓冲区从硬盘读取(此时缓冲区没有意义),如果设置的字节数组的大小小于缓冲区的大小,缓冲区才有意义。

改变默认缓冲区大小可以在构造方法中改变:BufferedOutputStream(new FileOutputStream("路径“),想改变的大小);

DataInputStream和DataOutputStream类

这两个类同样也是高级流,但是提供了多种写入和读出的方法,可以在写入的数据类型不同时调用不同的函数。

简单的写入文件实现(多种不同的写入函数)

public class TestDataOutput {
	public static void main(String[] args) throws IOException {
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:\\keshe\\c.txt"));
		dos.writeInt(250);
		dos.writeByte(34);
		dos.writeDouble(83.03);
		dos.writeChar('a');
		dos.writeUTF("emmm");
		dos.close();
	}
}

简单的读出文件实现(对应写入的顺序调用不同的函数读出)

public class TestDataInput {
	public static void main(String[] args) throws IOException {
		DataInputStream dis = new DataInputStream(new FileInputStream("C:\\keshe\\c.txt"));
		System.out.println(dis.readInt());
		System.out.println(dis.readByte());
		System.out.println(dis.readDouble());
		System.out.println(dis.readChar());
		System.out.println(dis.readUTF());
		dis.close();
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_40373090/article/details/82556008