6. 复制文本文件
读取源文件 FileRreader
写入到目的文件 FileWriter
两种文件复制方式,分别计算时间
第一个数组,写一个数组
利用缓冲区复制文件
第一行,写一行的操作
例程:复制文本文件
import java.io.*;
public class CopyText {
// 读取一个数组,写一个数组
public static void copyText1() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("F:\\Thinking.txt");
fw = new FileWriter("F:\\Thinking2.txt");
char[] buff = new char[1024];
int len = 0;
while ((len = fr.read(buff)) != -1) {
fw.write(buff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null)
fr.close();
} catch (IOException e) {
throw new RuntimeException("文件读取关闭失败");
}
try {
if (fw != null)
fw.close();
} catch (IOException e) {
throw new RuntimeException("文件写入关闭失败");
}
}
}
// 读取一个字符,写一个字符
public static void copyText2() {
FileReader fr = null;
FileWriter fw = null;
try {
fw = new FileWriter("F:\\Thinking2.txt");
fr = new FileReader("F:\\Thinking.txt");
int len = 0;
while ((len = fr.read()) != -1) {
fw.write((char) len);
}
} catch (Exception e) {
throw new RuntimeException("文件复制失败");
} finally {
try {
if (fr != null)
fr.close();
} catch (IOException e) {
throw new RuntimeException("文件读取关闭失败");
}
try {
if (fw != null){
fw.close();
}
} catch (IOException e) {
throw new RuntimeException("文件写入关闭失败");
}
}
}
//读取一行写一行的方式,利用的缓冲区对象
public static void copyText3(){
FileReader fr=null;
FileWriter fw=null;
BufferedReader bfr=null;
BufferedWriter bfw=null;
try {
fr=new FileReader("F:\\Thinking.txt");
fw=new FileWriter("F:\\Thinking3.txt");
bfr=new BufferedReader(fr);
bfw=new BufferedWriter(fw);
String sLine=null;
while((sLine=bfr.readLine())!=null){
bfw.write(sLine);
//bfw.write("\r\n");
bfw.newLine();
}
} catch (IOException e) {
throw new RuntimeException("文件复制失败");
}finally{
try {
if(bfr!=null);
bfr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(bfw!=null)
bfw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {