字节缓冲流和基本字节流读取文件(一个字节读取,一个字节数组读取)

package FourWaysToGetText;
import java.io.*;
public class FourWays {
/**
* 运用四种方式读写文件,按读取文件大小分为一次读取一个字节和一次读取一个字节数组,
* 按读取方式可以分为基本字节流和字节缓冲流(其实在使用上区别不大,只是字节缓冲流需要用到基本字节流对象)
* 自己缓冲的读取效率还是比基本字节流高的,大家可以读取大一些的文件,例如图片或大一点的文本,
* 可以比较他们在内存中所需要的运行时间。
*/
public static void main(String[] args) throws IOException {
Long start1 = System.currentTimeMillis();
method4();
Long finish1 = System.currentTimeMillis();
System.out.print("基本字节流复制文本所耗时间 (ms)");
System.out.print(finish1 - start1);//获得运行所需时间
}

//字节缓冲流一次读写一个字节数组
public static void method4() throws IOException {

BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("E:\itcast\creat.txt"));
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("Gzy_BasicJava\out5.txt"));
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
}

//字节缓冲流一次写入一个字节
public static void method3() throws IOException {
BufferedInputStream b1 = new BufferedInputStream(new FileInputStream("E:\itcast\creat.txt"));
BufferedOutputStream BO = new BufferedOutputStream(new FileOutputStream("Gzy_BasicJava\out5.txt"));
int len;
while ((len = b1.read()) != -1) {
BO.write(len);
}
b1.close();
BO.close();
}
//基本字节流一次读写一个字节
public static void method1() throws IOException {
FileInputStream in1 = new FileInputStream("E:\itcast\creat.txt");
FileOutputStream out1 = new FileOutputStream("Gzy_BasicJava\out1.txt");
int len;
while ((len = in1.read()) != -1) {
out1.write(len);
}
in1.close();
out1.close();
}
//基本字节流一次读写一个字节数组
public static void method2() throws IOException {
FileInputStream in2 = new FileInputStream("E:\itcast\creat.txt");
FileOutputStream out2 = new FileOutputStream("Gzy_BasicJava\out2.txt");
int len;
byte[] bytes = new byte[1024];
while ((len = in2.read(bytes)) != -1) {
out2.write(len);
}
out2.close();
in2.close();
}
}
原文地址:https://www.cnblogs.com/gzy918/p/13832859.html