一、通过节点流(InputStream、OutputStream)实现文件的复制:
/**
* @param pathTo
* :要保存复制内容的新文件路径,包含文件名及其后缀
* @param pathFrom
* :要复制的源文件路径,包含文件名及其后缀
* @author Beauxie
*/
static void copyFile(String pathTo, String pathFrom) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(new File(pathFrom));
os = new FileOutputStream(new File(pathTo));
byte[] bytes = new byte[1024];
int count = 0;
while ((count = is.read(bytes)) != -1) {
System.out.println(new String(bytes));
os.write(bytes, 0, count);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();// 关闭输入流,不然会浪费很多资源
is = null;
}
if (os != null) {
os.flush();// 刷新缓冲区中的内容
os.close();// 关闭输出流
os = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、通过处理流(BufferedReader 、BufferedWriter )实现文件复制:
/**
* 该方法通过处理流实现文件的复制
*
* @param pathFrom
* :需要复制文件的路径,包含文件名及其后缀
* @param pathTo
* :存放复制内容的文件路径,包含文件名及其后缀
* @author Beauxie
*/
private static void copyFile(String pathFrom, String pathTo) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
/*
* InputStream is=new FileInputStream(pathFrom); InputStreamReader
* ir=new InputStreamReader(is); br=new BufferedReader(ir);
*/
br = new BufferedReader(new InputStreamReader(new FileInputStream(
pathFrom)));
/*
* OutputStream os=new FileOutputStream(pathTo); OutputStreamWriter
* or=new OutputStreamWriter(os); bw=new BufferedWriter(or);
*/
bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(pathTo)));
String str = null;
while ((str = br.readLine()) != null) {
bw.write(str + "\r\n");
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
if (bw != null) {
bw.flush();
bw.close();
bw = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}