package com.hzq;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 文件输入输出流练习 分字节流和字符流 2010-05-11
*/
public class FileIO {
/**
* @param args
*/
public static void main(String[] args) {
File srcFile = new File("src.txt");// 源文件
File copyFile = new File("copyFile.txt");// 复制后的文件
// ****************************************
// *********使用字节流复制文件的标准代码*********
// *****************************************
try {
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(copyFile);
int b;
while ((b = in.read()) != -1) {// 当等于-1时读到文章末尾
out.write(b);
}
/*
* 关闭流
*/
out.close();
in.close();
// ****************************************
// *********以下代码加上缓存以提高读写效率*********
// *****************************************
// 方法 一 用buffer 过滤
BufferedInputStream iput = new BufferedInputStream(
new FileInputStream(srcFile));
BufferedOutputStream oput = new BufferedOutputStream(
new FileOutputStream(copyFile));
int c;
while ((c = iput.read()) != -1) {
oput.write(c);
}
/*
* 关闭流
*/
oput.close();
iput.close();
// 方法二自定义缓存
FileInputStream in2 = new FileInputStream(srcFile);
FileOutputStream out2 = new FileOutputStream(copyFile);
int b2;
byte[] buffe = new byte[512];// 缓存
while ((b2 = in2.read(buffe)) != -1) {// 当等于-1时读到文章末尾
out2.write(buffe);
}
/*
* 关闭流
*/
out2.close();
in2.close();
// ****************************************
// *********使用字符流读写文本文件*************
// *****************************************
BufferedReader reader = new BufferedReader(new FileReader(srcFile));
PrintWriter pw = new PrintWriter(copyFile);
String line;
while ((line = reader.readLine()) != null) {
pw.write(line);
}
/*
* 关闭流
*/
pw.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}