a- package demo.io;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- //复制java文件并改名
- public class CopyAndRename {
- public static void main(String[] args) throws Exception {
- File src = new File("f:\\Java review");
- File des = new File("F:\\复制文件并改名");
- des.mkdirs();
- copyFile(src,des); //复制函数如果运行的话,文件的重命名就失败为什么?
- rename(des);//把copyFile()函数屏蔽能运行成功,否则失败,就算文件已经存在也一样 为什么?
- System.out.println("改名完成...");
- }
- private static void rename(File des) {
- File[] files = des.listFiles();
- for(File f:files){
- if(f.isDirectory())
- rename(f);
- else{
- System.out.println(f.getPath());
- String newName = f.getPath().replaceAll("java", "txt");
- System.out.println(newName);
- System.out.println(f.renameTo(new File(newName)));
- }
- }
-
- }
- private static void copyFile(File src, File des) throws Exception {
- BufferedReader br = null;
- BufferedWriter bw = null;
- File[] files = src.listFiles();
- for(File f:files){
- if(f.isDirectory()){
- File newSrc = new File(des+"\\"+f.getName());
- System.out.println(newSrc);
- System.out.println(newSrc.mkdirs());
- copyFile(f,newSrc);
- }
- else if(f.getName().endsWith(".java")){
- br = new BufferedReader(new FileReader(f));
- bw = new BufferedWriter(new FileWriter(des+"\\"+f.getName()));
- String line = null;
- System.out.println(f);
- while((line = br.readLine())!=null){
- bw.write(line);
- bw.newLine();
- bw.flush();
- }
- System.out.println("done");
- }
- }
- if(null != br)
- br.close();
- if(null!=bw)
- br.close();
- }
- }
复制代码
|
|