看我的吧,大概思想和你一样
- /*
- * 1.编写一个程序,把一个目录里边的所有带.java文件拷贝到另一个目录中,拷贝成功后,
- * 把后缀名是.java的文件改为.txt文件。(要求有思路,有注释,有代码,需要注意的是:这个是先拷贝,拷贝成功后才可以改后缀名的)
- */
- import java.io.*;
- public class CopyDirs {
- public static void main(String[] args) throws IOException {
- File f1 = new File("a");
- File f2 = new File("b");
- CD(f1,f2);
-
- }
-
- public static void CF(File f1,File f2) throws IOException
- {
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));
- int len;
- byte[] buf = new byte[1024];
- while((len = bis.read(buf))!= -1)
- {
- bos.write(buf,0,len);
- bos.flush();
- }
- bis.close();
- bos.close();
- }
- public static void CD(File f1,File f2) throws IOException
- {
- if(f1.isDirectory())
- {
- if(!f2.exists())
- {
- f2.mkdir();
- }
- }
- File[] fs = f1.listFiles();
- for(File f: fs)
- {
- //需要注意的是:这个是先拷贝,拷贝成功后才可以改后缀名的
- if(f.isFile())
- {
- if(f.getName().endsWith("java"))
- {
- String j = f.getName();
- String jj = f2.getPath()+f.separator+j;
- File fn =new File(jj);
- CF(f,fn);
- String n = jj.subSequence(0, j.length()-4)+".txt";
- File fn1 = new File(n);
- fn.renameTo(fn1);
- }
- else
- {
- String j = f.getName();
- String jj = f2.getPath()+f.separator+j;
- File fn = new File(jj);
- CF(f,fn);
- }
- }
- if(f.isDirectory())
- {
- String j = f.getName();
- String jj = f2.getPath()+f.separator+j;
- File fn = new File(jj);
- CD(f,fn);
- }
- }
- }
-
- }
复制代码 |