黑马程序员技术交流社区

标题: 拷贝并改名 [打印本页]

作者: 木子小四    时间: 2016-4-14 13:03
标题: 拷贝并改名
编写一个程序,把这个目录里边的所有的带.java文件都拷贝到另一个目录里边,拷贝成功以后,把后缀名是.java改成.txt
===========================================
  1. package com.heima.test;

  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;

  9. public class Test3 {

  10.         /**
  11.          * 9:编写一个程序,把这个目录里边的所有的带.java文件都拷贝到另一个目录里边,拷贝成功以后,把后缀名是.java改成.txt
  12.          * @throws IOException
  13.          *
  14.          *
  15.          */
  16.         public static void main(String[] args) throws IOException {
  17.                 //获取文件路径
  18.                 File f1 = new File("F:/1");
  19.                 //目标路径
  20.                 File f2 = new File("F:/2");
  21.                 //创建文件对象数组
  22.                 File[] f3 = f1.listFiles();
  23.                 //遍历数组如果是文件,而且,后缀名是.Java,就复制
  24.                 for (File f4 : f3) {
  25.                         if(f4.getName().endsWith(".java")){
  26.                                 //==================================
  27.                                                 String s = f4.getName().replace(".java", ".txt");
  28.                                                 System.out.println(s);
  29.                                        
  30.                                
  31.                                 BufferedInputStream bis =
  32.                                                 new BufferedInputStream(new FileInputStream(f4));
  33.                                 BufferedOutputStream bos =
  34.                                                 new BufferedOutputStream(new FileOutputStream(new File(f2,s)));
  35.                                 int b;
  36.                                 while ((b=bis.read())!=-1){
  37.                                         bos.write(b);
  38.                                 }
  39.                                 //关流
  40.                                 bis.close();
  41.                                 bos.close();
  42.                         }
  43.                 }
  44.                 System.out.println("复制好了..");
  45.                
  46.         }

  47. }
复制代码





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