Java编写文件拷贝

来源:互联网 发布:淘宝包店名字 编辑:程序博客网 时间:2024/06/13 03:52

public class TestDemo {

      public static void main(String[]args) throws Exception {

            File inFile = new File("d:"+File.separator+"demo"+File.separator+"hello.jpg") ; 

           if (!inFile.exists()) { 

                 System.out.println("拷贝的源文件不存在,程序退出!");

                 System.exit(1);

          }

          File outFile = new File("d:"+File.separator+"mldn"+File.separator+"nihao"+

          File.separator+"hello"+File.separator+"my.jpg") ;

          copy(inFile,outFile) ;

    }

      public static boolean copy(FileinFile,File outFile) throws Exception {

      InputStream input = null ;// 实现输入数据读取

     OutputStream output = null ;// 实现输出数据保存

     try {

    // 需要考虑目标文件的文件夹生成问题

     if (!outFile.getParentFile().exists()) {

           outFile.getParentFile().mkdirs() ;

      }

      byte data [] =new byte [2048] ;

     // 分别实例化输入流与输出流

     input = new FileInputStream(inFile) ;

     output = new FileOutputStream(outFile) ;

      int temp = 0 ;// 保存每次读取进来的数据

    // 将数据读取到数组之中,而后返回读取的个数

     while((temp =input.read(data)) != -1) {

           output.write(data,0,temp);

     }

           return true ;

    } catch (Exceptione) {

          throw e ;

     } finally {

         if (input !=null) {

         input.close();

     }

      if (output !=null) {

          output.close();

       }

    }

  }

}


1 0
原创粉丝点击