* 文本拷贝 将 D:/TestFile/note.txt拷贝到 D:/TestFile/backup/下
* 文本适合用字符流处理 (因为编码的不同所以一个字符可能占不确定个字节,不适合用字节流处理)
* 因此采用FileReader和FileWriter来完成拷贝
package filecopy;
import java.io.*;
/**
* 文本拷贝 将 D:/TestFile/note.txt拷贝到 D:/TestFile/backup/下
* 文本适合用字符流处理
* 因此采用FileReader和FileWriter来完成拷贝
*/
public class TextCopy {
public static void main(String[] args) {
//先在TestFile目录下建一个backup文件夹
File file = new File("D:/TestFile/backup");
file.mkdir(); //创建一级目录
//创建字符输入流
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
fileReader = new FileReader("D:/TestFile/note.txt");
fileWriter = new FileWriter("D:/TestFile/backup/note.txt");
char[] chars = new char[32];
int readLen = 0;
while( (readLen = fileReader.read(chars)) != -1 ){
//因为可能读不满32个字符,所以用指定长度的方式
fileWriter.write(chars,0,readLen);
}
//除了这种方式外还可以一个字符一个字符的读写,那样效率较低
System.out.println("note.txt 拷贝完毕");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
//关闭输入流
fileReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
//关闭输出流
fileWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}