使用BufferedReader 和 BufferedWriter 完成文本文件拷贝
package com.hspedu.writer_;
import java.io.*;
public class BufferedCopy_ {
public static void main(String[] args) {
//BufferedReader 和BufferedWriter 是按照字符操作
//不要去操作二进制文件(声音,视频,doc,pdf),可能造成文件损坏
String srcFilePath = "e:\\new3.txt";
String destFilePath = "e:\\news3.txt";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try {
br = new BufferedReader(new FileReader(srcFilePath));
bw = new BufferedWriter(new FileWriter(destFilePath));
//读取文件
//readLine 读取一行内容,没有换行
while ((line = br.readLine()) != null) {
//每读取一行就写入
bw.write(line);
//插入一个换行符
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if(br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedOutputStream 和 BufferedInputStream使用
package com.hspedu.outputstream_;
import java.io.*;
//演示使用BufferedOutputStream 和 BufferedInputStream使用
//完成二进制拷贝
//也可以操作文本文件
public class BufferedCopy02 {
public static void main(String[] args) {
String srcFilePath = "e:\\aa.png";
String destFilePath = "d:\\aa.png";
//创建BufferedOutputStream 和 BufferedInputStream对象
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//因为 FileInputStream 是 InputStream 子类
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
//循环读取文件,并写入到destFilePath
byte[] buff = new byte[1024];
int readLine = 0;
//当返回-1时,文件读取完毕
while((readLine = bis.read(buff)) != -1) {
bos.write(buff, 0, readLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭外层处理流,底层会去关闭节点流
try {
if(bis != null) {
bis.close();
}
if(bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}