摘要:文件夾不能直接復制,如果是文件夾需要先創建文件夾,然后再復制文件。
import java.io.*;
public class Copy {
//用於文件夾和文件的復制
public static void main(String[] args) throws IOException {
//要復制的文件或文件夾路徑
String src = "E:\\Test1";
//復制文件或文件夾到目標文件夾下,注意這里復制的可能是文件也可能是文件夾,但是目標一定是文件夾
String dest = "E:\\test";
copy(src, dest);
}
public static void copy(String src, String dest) throws IOException {
File file = new File(src);
if(!file.exists()){
//可以起到一個拋出異常中斷程序的效果
throw new RuntimeException("找不到指定路徑下的文件或文件夾"+src);
}
//初始化I/O流
InputStream in = null;
OutputStream out = null;
//如果文件夾是目錄,則在指定路徑下新建目錄,如果是文件則直接復制
if(file.isDirectory()){
File[] files = file.listFiles();
String cur = dest + File.separatorChar + file.getName();
File file1 = new File(cur);
if(!file1.mkdir()){
throw new RuntimeException("非法路徑"+dest);
}
for(File file2 : files){
copy(file2.getAbsolutePath(), file1.getAbsolutePath());
}
}else{
in = new FileInputStream(file);
out = new FileOutputStream(dest + File.separatorChar + file.getName());
//緩存數組
byte[] a = new byte[1024];
int len = -1;
while((len = in.read(a)) != -1){
out.write(a);
}
//將緩存寫入目標文件
out.flush();
//先創建先釋放,后創建后釋放
out.close();
in.close();
}
}
}
學習:使用throw關鍵字拋出異常,既可以起到異常提示的作用,還可以起到中斷程序的作用。
