欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

BufferedOutputStream与BufferedInputStream

程序员文章站 2024-03-04 20:48:30
...

喜欢在下面评论区扣1支持下呗

字节缓冲输出流: BufferedOutputStream (OutputStream out)

public class BufferStreamDemo {
	public static void main(String[] args) throws IOException {
		//字节缓冲输出流: BufferedOutputStream (OutputStream out)
		FileOutputStream fos = new FileOutputStream( "demo.txt");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		//可将上面两句转化为一句
		//BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream( "demo.txt"));
		
		//写数据
		bos.write( "hello\r\n".getBytes());
		bos.write( "world\r\n".getBytes());
		
		//释放资源
		bos.close();
	}
}

字节缓神输入流: BufferedInputStream (InputStream in)

public class BufferedInputStreamDemo {
	public static void main(String[] args) throws IOException {
		//字节缓冲输入流: BufferedInputStream (InputStream in)
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("demo.txt"));
		
		//方法一:一次读取一个字节数据.
		int x;
		while ((x=bis.read())!=-1) {
			System.out.print((char)x);//直接输出bis.read()出现乱码
		}
		
		//方法二:一次读取一个字节数组数据
		byte[] yy = new byte[1024];
		int y;
		while ((y=bis.read(yy))!=-1) {
			System.out.print(new String(yy,0,y));
		}
		
		//释放资源
		bis.close();
	}
}

BufferedOutputStream与BufferedInputStream