java 文件复制
Java复制文件有多种方式,本文只列举了其中的一种。
该程序的效果是:获取指定文件夹下的指定类型的文件,然后复制到指定的文件夹下。
PS:该程序一次只能复制一种类型
public class CopyFileExample {
public static void main(String[] args) throws IOException {
//获取键盘的输入
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入原文件路径:");
String oldPath = buffer.readLine();
System.out.println("请输入复制后路径:");
//该路径不能在源文件的路径下,否则就会把newPath目录下的文件覆盖,大小为0kb。
String newPath = buffer.readLine()+"\\";
System.out.println("请输入复制的文件类型:");
String fileType = buffer.readLine();
File files=new File(oldPath);
getAllFile(files,newPath,fileType);
System.out.println("复制成功");
}
//获取文件名称的方法
public static void getAllFile(File file,String newPath,String fileType){
File[] files = file.listFiles();
for (File fileName : files) {
if(fileName.isDirectory()){
//如果是文件夹
getAllFile(fileName,newPath,fileType);
}else{
//如果是文件
//获取文件的绝对路径
String name = fileName.getAbsolutePath();
if(name.endsWith(".md")){
//通过获取的路径进行文件的复制
//调用复制的方法
fileCopy(name,newPath);
}
}
}
}
//文件复制方法
public static void fileCopy(String str,String newPath){
//获取文件名称
String substring = str.trim().substring(str.lastIndexOf("\\") + 1);
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader(str);
fw=new FileWriter(newPath+substring);
int len=0;
char[] ch=new char[1024];
while((len=fr.read(ch))!=-1){
fw.write(ch,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//防止空指针异常
if(fw!=null&&fr!=null){
try {
fw.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
如有问题欢迎指正