黑马程序员技术交流社区

标题: 如何优化代码? [打印本页]

作者: 李前进    时间: 2014-5-8 16:35
标题: 如何优化代码?
如何用renameTo方法优化下面的代码?

  1. package com.itheima.intview;
  2. import java.io.*;

  3. public class Jad2Java
  4. {
  5.         public static void main(String[] args) throws Exception
  6.         {
  7.                 File srcDir = new File("G:\\java test\\day01");
  8.                 if(!(srcDir.exists() && srcDir.isDirectory()))
  9.                         throw new Exception("目录不存在");

  10.                 File[] files = srcDir.listFiles(new FilenameFilter()
  11.                 {
  12.                         public boolean accept(File dir, String name)
  13.                         {
  14.                                 return name.endsWith(".java");
  15.                         }
  16.                  
  17.                 });
  18.   
  19.                 System.out.println(files.length);
  20.                 File destDir = new File("C:\\day01");
  21.                 if(!destDir.exists())
  22.                         destDir.mkdir();
  23.                 for(File f :files)
  24.                 {
  25.                         FileInputStream  fis = new FileInputStream(f);
  26.                         String destFileName = f.getName().replaceAll("\\.java", ".txt");
  27.                         FileOutputStream fos = new FileOutputStream(new File(destDir,destFileName));
  28.                         copy(fis,fos);
  29.                         fis.close();
  30.                         fos.close();
  31.                 }
  32.         }

  33.         private static void copy(InputStream ips,OutputStream ops) throws Exception
  34.         {
  35.                 int len = 0;
  36.                 byte[] buf = new byte[1024];
  37.                 while((len = ips.read(buf)) != -1)
  38.                 {
  39.                         ops.write(buf,0,len);
  40.                 }
  41.         }

  42. }

复制代码

作者: 李前进    时间: 2014-5-8 16:38
如何用renameTo拷贝文件并且重命名?例如:怎么把"G:\\java test\\day01"文件夹中所有的java文件复制到"C:\\day01",并且把后缀名改成.txt?




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2