关于java I/O流的总结之字节流

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

将I/O流的处理看成两类一类是对于字节的处理,另一类是对于字符的处理。对于字符的处理有父类IputStream、OutputStream两个对于字符的处理的两个父类是Reader与Writer。

下面分开成两部分来进行总结:

    1.字节处理

      字节处理方式可以处理任何类型的文件。字节处理方式用到最多的就是FileInputStream、FileOutputStream。下面以具体代码来说明使用,要注意的也写在代码注释里面:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;

public class test {

	public static void main(String[] args) throws IOException {
		//copy1();
		//copy2();
		//copy3();
		//copy4();
	}

	private static void copy4() throws FileNotFoundException, IOException {
		/*
		 * 这里用到了BufferedInputStream 其中也内置了一个直接数组其大小是1024*8=8192 存在内存中,一次从硬盘中读取8192
		 * 个字节到内存中再去一个字节出来用
		 * BufferedOutputStream 也是它不会直接写入而是等到8192个字节都写满了过后再从内存里面写到硬盘
		 * BufferedOutputStream 如果没有写满不会自己写到内存里面必须用Flush或则close,前者刷新缓冲区过后还可以继续写入,
		 * 后者是在关闭流之前再刷新一次缓冲区
		 * 
		 */
		BufferedInputStream fin=new BufferedInputStream(new FileInputStream("hello"));
		//括号里的可以不加对象名称了
		BufferedOutputStream fout= new BufferedOutputStream(new FileOutputStream("test.txt",true));
		
		int i;
		while((i=fin.read())!=-1) {
			fout.write(i);
			fout.flush();
		}
		fin.close();
		fout.close();
	}

	private static void copy3() throws FileNotFoundException, IOException {
		FileInputStream fin=new FileInputStream("hello");
		FileOutputStream fout= new FileOutputStream("test.txt",true);
		int i;
		byte [] arr=new byte [1024*8];
		while((i=fin.read(arr))!=-1) {
			fout.write(arr, 0, i);
		}
		fin.close();
		fout.close();
	}

	private static void copy2() throws FileNotFoundException, IOException {
		/*
		 * 整组拷贝
		 * available()方法返回文件可以read到的字节个数
		 * read(arr)read后面还可以加一个数组直接读和写一个数组的内容
		 * 不推荐使用这种方法文件太大会使得内存溢出
		 */
		FileInputStream fin=new FileInputStream("hello");
		FileOutputStream fout= new FileOutputStream("test.txt",true);
		byte [] arr=new byte[fin.available()];
		fin.read(arr);
		fout.write(arr);
		fin.close();
		fout.close();
	}

	private static void copy1() throws FileNotFoundException, IOException {
		
		/*
		 * 一个字节一个字节拷贝
		 */
		FileInputStream fin=new FileInputStream("hello");//括号里还可以直接加File类型的变量
		FileOutputStream fout= new FileOutputStream("test.txt",true);//如果无文件夹自动创建如果有自动擦除原有文件后写入,
		//如果要接在后面加上true
		int i;/*read()读入单个字节函数返回的是int类型的数,当读到文件的结尾的时候返回-1,这也是为什么read()返回值是int二不是Byte的
		*原因,当文件中间就有-1的时候文件读不完
		*/
		while((i=fin.read())!=-1){
			fout.write(i);//write()一个字节一个字节的写入
		}
		fin.close();
		fout.close();
	}

}
里面需要注意的就是BufferedInputStream,和BufferedOutputStream两个,下面看看原理图:

猜你喜欢

转载自blog.csdn.net/zcawesome/article/details/80525294