记录自己的学习过程..
package what;
import java.io.*;
class CopyFiles
{
private String pathFrom; //被复制文件或目录的路径名
private String pathTo; //指定目录的路径名
private String p; //复制后文件或目录的新路径名
private int index; //被复制文件或目录名在原路径名中的索引
public void copy(String pathF,String pathT)
{
this.pathFrom=pathF;
this.pathTo=pathT;
index=pathFrom.lastIndexOf("\\");
if(new File(pathFrom).isDirectory())
this.copyD(pathFrom);
else
this.copyF(pathFrom);
}
public void copyF(String path) //复制文件
{
p=pathTo+File.separator+path.substring(index);
try(
FileInputStream fis=new FileInputStream(path);
FileOutputStream fos=new FileOutputStream(p))
{
byte[] bbuf=new byte[512];
int hasRead=0;
while((hasRead=fis.read(bbuf))>0)
{
fos.write(bbuf,0,hasRead);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void copyD(String path) //复制目录
{
p=pathTo+path.substring(index);
new File(p).mkdir(); //建立新目录
String[] fileList=new File(path).list(); //获得File对象下的文件名或目录名
for(String f:fileList)
{
f=path+File.separator+f; //须将f改为绝对路径名,以判断是目录或文件
if(new File(f).isDirectory())
this.copyD(f);
else
this.copyF(f);
}
}
}
public class Example
{
public static void main(String[] args)throws Exception
{ // 依次输入原文件或目录、指定目录的路径名
new CopyFiles().copy("E:\\编程程序\\what\\bin\\what\\Example.class","E:\\编程程序\\what复制件");
}
}