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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y41992910/article/details/88528321

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();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/y41992910/article/details/88528321