1. 通过字节流实现文件的拷贝
/*** 通过字节流实现文件的拷贝
*@paramsourcePath 源文件路径
*@paramtargetPath 目标文件路径*/
public static voidcopyFileByStream(String sourcePath,String targetPath){//源文件路径
File source = newFile(sourcePath);//目标文件路径
File target = newFile(targetPath);//如果源文件不存在则不能拷贝
if(!source.exists()){return;
}//如果目标文件目录不存在则创建
if(!target.getParentFile().exists()){
target.getParentFile().mkdirs();
}try{//实现文件的拷贝
InputStream inputStream = newFileInputStream(source);
OutputStream outputStream= newFileOutputStream(target);int temp = 0;//每次读取1024个字节
byte[] data = new byte[1024];//将每次读取的数据保存到字节数组里面,并且返回读取的个数
while ((temp = inputStream.read(data)) != -1){//输出数组
outputStream.write(data,0,temp);
}
inputStream.close();
outputStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
View Code
2. 通过字符流实现文件拷贝(使用字符流只能拷贝文本文件)
/*** 通过字符流实现文件的拷贝
*
*@paramsourcePath 源文件路径
*@paramtargetPath 目标文件路径*/
public static voidcopyFileByReaderAndWriter(String sourcePath, String targetPath) {//源文件路径
File source = newFile(sourcePath);//目标文件路径
File target = newFile(targetPath);//如果源文件不存在则不能拷贝
if (!source.exists()) {return;
}//如果目标文件目录不存在则创建
if (!target.getParentFile().exists()) {
target.getParentFile().mkdirs();
}
FileReader in= null;
FileWriter out= null;try{//字符输入流和字符输出流
in = newFileReader(source);
out= newFileWriter(target);char[] c = new char[1024];int temp = 0;//每次读取1024个字符
while ((temp = in.read(c)) != -1) {//输出到文件
out.write(c, 0, temp);
}
}catch(IOException e) {
e.printStackTrace();
}finally{//关闭流
try{if (in != null) {
in.close();
}if (out != null) {
out.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
View Code
3. 通过字节缓冲流实现文件拷贝
/*** 通过字节缓冲流实现文件的拷贝
*
*@paramsourcePath 源文件路径
*@paramtargetPath 目标文件路径*/
public static voidcopyFileByBuffered(String sourcePath, String targetPath){//源文件路径<