- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- /*
- * 需求:拷贝一个目录中后缀为.java的文件,遍历拷贝的这个目录,并将该目录下所有后缀为.java的文件改为后缀为.txt
- * */
- public class ErgodicFile {
-
- public static void main(String[] args)throws IOException
- {
- File destDir=new File("C:/JAVA1");
- File srcDir=new File("C:/JAVA");
- destDir.mkdir();
- copyDir(srcDir,destDir);
- Ergodic(destDir);
-
- }
- public static void Ergodic(File dir)
- {
- File[] files = dir.listFiles();
- for (File file : files) {
- if (file.isDirectory())
- Ergodic(file);
- else {
- int index = file.getAbsolutePath().indexOf(".java");
- if (index != -1) {
- String AbsPath = file.getAbsolutePath().substring(0, index) + ".txt";
- File dest = new File(AbsPath);
- file.renameTo(dest);
- }
- }
- }
- }
-
- public static void copyDir(File srcDir,File destDir) throws IOException
- {
- File files[]=srcDir.listFiles();
- for(File file:files)
- {
- if(file.isDirectory()&&file.listFiles().length!=0){
- File f=new File(destDir.getAbsolutePath()+File.separator+file.getName());
- f.mkdir();
- copyDir(file,f);
- }
- else
- {
- if(!isEndWithJava(file))
- continue ;
- File f=new File(destDir.getPath()+File.separator+file.getName());
- if(!f.exists())
- f.createNewFile();
- copyFile(file,f);
- }
- }
- }
-
- public static void copyFile(File src,File dest) throws IOException
- {
- FileInputStream fin=new FileInputStream(src);
- FileOutputStream fos=new FileOutputStream(dest);
-
- byte[] b=new byte[1024];
- int len;
- while((len=fin.read(b))!=-1)
- {
- fos.write(b,0,len);
- }
- fos.close();
- fin.close();
- }
-
- private static boolean isEndWithJava(File file)
- {
- return file.getName().endsWith(".java");
- }
- }
复制代码 |