编程实现文件复制和重命名
编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad。
package com.alex.test3;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Java2Jad {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File javaFile = new File("D:\\java");
File[] javaFiles=null;
if(javaFile.exists()&&javaFile.isDirectory()){
javaFiles=javaFile.listFiles(
new FileFilter(){
public boolean accept(File pathname) {
return pathname.getName().endsWith(".java");
}
});
copyAndRenameFiles(javaFiles,"D:\\jad","\\.java",".jad");
System.out.println("copy successful...");
}else{
throw new Exception("there are not such directroy");
}
}
public static void copyAndRenameFiles(File[] sourceFiles,String targetFilePath,String originalSuffix,String targetSuffix){
File targetFile = new File(targetFilePath);
FileWriter fw = null;
FileReader fr = null;
if(!targetFile.isDirectory()){
targetFile.mkdir();
}
try {
for(File file:sourceFiles){
fw = new FileWriter(targetFilePath+"\\"+file.getName().replaceAll(originalSuffix, targetSuffix));
int len=0;
char[] cbuf=new char[(int)file.length()];
fr = new FileReader(file);
while((len=fr.read(cbuf))!=-1){
fw.write(cbuf,0,len);
}
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
还没有评论,来说两句吧...