public class IoDemo03 {
public static void main(String[] args) {
FileReader fReader = null;
FileWriter fWriter = null;
try {
fReader = new FileReader("abc.txt");
fWriter = new FileWriter("dest.txt");
//这种方法也可写入数据
fWriter.write(" 春江花月夜 \r\n ");
//设置缓冲区,提高速率,只能使用char类型,不加缓冲,挨个字符读
char[] buffer = new char[1024];
int temp = 0;
while((temp = fReader.read(buffer)) != -1) {
//fWriter.write(buffer);也可
fWriter.write(buffer,0,temp);
}
//“\r\n”是win中的换行符,append()方法是在文本后面追加内容。
fWriter.append("\r\ncopy结束了");
fWriter.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(fWriter!=null) {
fWriter.close();
}
if(fReader!=null) {
fReader.close();
}
} catch (Exception e2) {
}
}
}
}
加入缓冲的字符流:
/**
* 缓冲字符流。copy工具
*/
public class IoDemo04 {
public static void main(String[] args) {
IoDemo04.copyFile("abc.txt", "dest.txt");
}
public static void copyFile(String src, String des) {
BufferedReader bReader = null;
BufferedWriter bWriter = null;
try {
bReader = new BufferedReader(new FileReader(src));
bWriter = new BufferedWriter(new FileWriter(des));
//按照行为单位读取
String temp = "";
while((temp = bReader.readLine()) != null) {//当为空时表示读完
bWriter.write(temp);
bWriter.newLine();//换行
}
bWriter.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bReader != null) {
bReader.close();
}
if(bWriter !=null) {
bWriter.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}