黑马程序员技术交流社区

标题: 分享代码(将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt) [打印本页]

作者: 小泽    时间: 2015-2-21 19:55
标题: 分享代码(将指定目录下所有.java文件拷贝到另一个目的中,并将扩展名改为.txt)
  1. public class Test9 {

  2.         /**
  3.          * @param args
  4.          * @throws IOException
  5.          * @throws FileNotFoundException
  6.          */
  7.         public static void main(String[] args) throws FileNotFoundException,
  8.                         IOException {

  9.                 String sfile = "D:\\java";// 源文件路径
  10.                 String dfolder = "D:\\txt";// 目的文件路径

  11.                 File src = new File(sfile);
  12.                 File des = new File(dfolder);

  13.                 if (!des.exists()) { // 判断目的文件是否存在,不存在就创建
  14.                         des.mkdirs();
  15.                 }
  16.                 File[] files = src.listFiles(); // 获取源文件夹中的文件。

  17.                 for (File f : files) { // 遍历文件。
  18.                         String str = f.getName();// 将文件中的Java文件名赋给str。
  19.                         copyFile(sfile + "\\" + str, dfolder + "\\" + str);// 调用方法copyFile复制java文件并更改拓展名。
  20.                 }

  21.         }

  22.         /**
  23.          * 使用字节流复制.java文件并把拓展名改为.txt。
  24.          *
  25.          * @throws FileNotFoundException
  26.          * @throws IOException
  27.          * @param str1 接收源文件地址。
  28.          * @param str2 接收目的文件地址。         
  29.          */
  30.         public static void copyFile(String str1, String str2)
  31.                         throws FileNotFoundException, IOException {

  32.                 StringBuilder sbl = new StringBuilder();// 创建一个容器,用来把源文件拓展名更改为.txt并转化成String。
  33.                 sbl.append(str2);
  34.                 sbl.replace(sbl.length() - 5, sbl.length(), ".txt");
  35.                 String str = sbl.toString();

  36.                 FileInputStream fis = new FileInputStream(str1);// 定义读取字节流。
  37.                 BufferedInputStream bufis = new BufferedInputStream(fis);// 定义读取字节流缓冲区。

  38.                 FileOutputStream fos = new FileOutputStream(str);// 定义写入字节流。
  39.                 BufferedOutputStream bufos = new BufferedOutputStream(fos);// 定义写入字节流缓冲区。

  40.                 int ch = 0;
  41.                 while ((ch = bufis.read()) != -1) { // 一次读取并写入一个字节。
  42.                         bufos.write(ch);
  43.                 }
  44.                 bufos.close();// 关闭流
  45.                 bufis.close();// 关闭流
  46.         }

  47. }
复制代码


欢迎大家指导。
作者: 小泽    时间: 2015-2-21 20:50
谢了            




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