java BIO 读取文件和写出到文件


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class BIOTest {

//	public static void main(String[] args) {
//		try {
//			//BIO方式读取文件
//			String pathname  = "D:\\add.txt";
//			File file = new File(pathname);
//			FileInputStream fileInputStream = new FileInputStream(file);
//			BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
//			//相对当前位置的偏移量
//			int off = 0;
//			//读取的长度,单位为字节
//			int len = 1024;
//			//读取的数据存储到该字节数组
//			//数组初始化之后,会有1024个字节,默认值为0。所以下面读取数据到b字节数组的时候,假如读取的长度不够,会有0填充的问题。
//			//所以具体要从b中读取多少个数据,要看len= bufferedInputStream.read(b, off, len)中,b到底从输入流中读取到了多少字节,也就是Len的值为多少
//			//以下的写法就是正常的,不会出现message中有乱码或者0填充的情况。
//			byte[] b = new byte[1024];
//			String message = "";
//			while ((len= bufferedInputStream.read(b, off, len)) != -1) {
//				message = message + new String(b, 0, len);
//				//这种写法就是错误的,会出现0填充的情况
//				//message = message + new String(b);
//			}
//			System.out.println(message);
//			bufferedInputStream.close();
//			fileInputStream.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	public static void main(String[] args) {
		try {
			//BIO方式读取文件,写出文件
			String pathname  = "D:\\add.txt";
			File file = new File(pathname);
			FileInputStream fileInputStream = new FileInputStream(file);
			BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
			
			FileOutputStream fileOutputStream = new FileOutputStream("D:\\add222.txt");
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
			//相对当前位置的偏移量
			int off = 0;
			//读取的长度,单位为字节
			int len = 1024;
			//读取的数据存储到该字节数组
			//数组初始化之后,会有1024个字节,默认值为0。所以下面读取数据到b字节数组的时候,假如读取的长度不够,会有0填充的问题。
			//所以具体要从b中读取多少个数据,要看len= bufferedInputStream.read(b, off, len)中,b到底从输入流中读取到了多少字节,也就是Len的值为多少
			//以下的写法就是正常的,不会出现message中有乱码或者0填充的情况。
			byte[] b = new byte[1024];
			while ((len= bufferedInputStream.read(b, off, len)) != -1) {
				bufferedOutputStream.write(b, 0, len);
			}
			bufferedInputStream.close();
			fileInputStream.close();
			
			bufferedOutputStream.close();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值