- 目的:
把源文件中的内容拷贝一份至目标文件。

- 思想:
- 定义一个类完成所有的前提条件,和文件拷贝的具体内容;
- 因为要把源文件的内容拷贝到目标文件,操作的是文件的内容,所以需要使用输入输出流,字节流使用范围比较广泛,此处使用字节流;
字节输入流InputStream,字节输出流OutputStream; - 前提1:先从源文件中读取内容,此时要保证的是源文件必须存在,只有源文件存在才能从中读取内容;
- 前提2:把读取到内容输出到目标文件,此时要确保所给文件的父路径都存在,如果不存在,则创建所有的目录;
- 完成具体拷贝。一边从源文件读取数据,一边输出到目标文件。
(1)创建文件的输入输出流对象;
(2)从源文件中读取数据(read),直到源文件为空;
(3)将读到的数据输出(writer)到目标文件。
- 具体代码:
package www.filecopy;
import java.io.*;
class FileCopyUtil {
private FileCopyUtil() {
}
public static boolean sourceFileIsExists(String sourcePath) {
File sourceFile = new File(sourcePath);
return sourceFile.exists();
}
public static void createParentDir(String destPath) {
File destFile = new File(destPath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
}
public static boolean fileCopy(String sourcePath, String descPath) throws IOException {
File inFile = new File(sourcePath);
File outFile = new File(descPath);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(inFile);
outputStream = new FileOutputStream(outFile);
byte[] bytes = new byte[1024];
int len = 0;
long start = System.currentTimeMillis();
while ((len = inputStream.read(bytes)) != -1){
outputStream.write(bytes,0,len);
}
long end = System.currentTimeMillis();
System.out.println("拷贝文件所花费的时间:"+(end-start));
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}finally {
inputStream.close();
outputStream.close();
}
return true;
}
}
public class FileCopy {
public static void main(String[] args) throws IOException {
String sourcePath = File.separator+"E:"+File.separator
+"picture"+File.separator+"666"+File.separator+"888"+File.separator+"write.txt";
String destPath = File.separator+"E:"+File.separator
+"picture"+File.separator+"666"+File.separator+"888"+File.separator+"test2.txt";
if (FileCopyUtil.sourceFileIsExists(sourcePath)){
FileCopyUtil.createParentDir(destPath);
if (FileCopyUtil.fileCopy(sourcePath,destPath)){
System.out.println("文件拷贝成功");
}else {
System.out.println("文件拷贝失败");
}
}else{
System.out.println("文件不存在");
}
}
}