使用缓冲字节流会大大提升效率,它的使用需要建立在其他字节流基础上。
package homework;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class T {
public static void main(String[] args) {
File file = new File("C:\\Users\\wym\\Desktop\\JDK 1.6 API.chm");
BufferedInputStream bufferedInputStream = null;//大大提高文件运行效率
FileInputStream fileInputStream = null;
long start = System.currentTimeMillis();//获取当前的毫秒值
try {
byte b[] = new byte[1024];
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);//将文件字节流包装
while(bufferedInputStream.read(b)!=-1){
}
long end = System.currentTimeMillis();//获取结束时的毫秒值
System.out.println(end - start);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fileInputStream!=null)
{
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bufferedInputStream != null)
{
try {
bufferedInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package homework;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo2 {
public static void main(String[] args) {
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
File file = new File("word.txt");
try {
fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);//包装文件输出流
String string = "天生我材必有用,千金散尽还复来";
byte[] b = string.getBytes();
bufferedOutputStream.write(b);
bufferedOutputStream.flush();//刷新。强制将文件数据写入缓冲区中,即使缓冲区没有满
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fileOutputStream!=null)
{
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bufferedOutputStream!=null)
{
try {
bufferedOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}