IO流看了这么多天还是一知半解,实际编写一个复制文件的代码之后了解清楚多了
package Day_6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
copyFolder("f:/new", "f:/new1");
}
public static void Copy_File(String absolutePath,String absolutePath2){
File src = new File(absolutePath);//源文件地址
File dest = new File(absolutePath2);//目标文件地址
byte [] data = new byte[1048576];
FileInputStream fis = null;//输入流
FileOutputStream fos = null;//输出流
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
while(true){
int a = fis.read(data);
if(a == -1)break;
fos.write(data,0,a);
}
fis.close();
fos.close();
System.out.println("done");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFolder(String srcFolder,String destFolder ){
File src = new File(srcFolder);
File dest = new File(destFolder);
if(!src.exists()){
return;
}
if(src.isFile()){//是文件
return;
}
if(dest.isFile()){
return;
}
if(!dest.exists()){
dest.mkdirs();
}
//遍历并复制
File[] fs = src.listFiles();
for(int i = 0; i < fs.length; i++){
if(fs[i].isFile()){//如果是文件
File newDest = new File(dest,fs[i].getName());//File(path,name)
System.out.println(fs[i].getAbsolutePath());
System.out.println(newDest.getAbsolutePath());
Copy_File(fs[i].getAbsolutePath(),newDest.getAbsolutePath());//复制文件
copyFolder(fs[i].getAbsolutePath(), newDest.getAbsolutePath());
}
if(fs[i].isDirectory()){//如果是目录
File newDest = new File(dest,fs[i].getName());
System.out.println(newDest.getAbsolutePath());
copyFolder(fs[i].getAbsolutePath(), newDest.getAbsolutePath());
}
}
}
}