FileInput/OutputStream 复制文件

  1. package example;  
  2. /** 
  3.  * 文件的拷贝. 
  4.  */  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.OutputStream;  
  11.   
  12. public class TestDemo {  
  13.     public static void main(String[] args) {  
  14.         String srcPath = "e:\\test.txt";  
  15.         String destPath = "e:\\msg\\info.txt";  
  16.         try {  
  17.             copyFile(srcPath,destPath);  
  18.         } catch (Exception e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.     }  
  22.       
  23.     /** 
  24.      * 利用字节流来实现文件的复制(字节流可以处理一切数据) 
  25.      * @param srcPath : 源文件路径 
  26.      * @param destPath : 目标文件路径 
  27.      * @throws Exception 
  28.      */  
  29.     public static void copyFile(String srcPath,String destPath) throws Exception{  
  30.         //构建源文件和目标文件的File对象  
  31.         File src = new File(srcPath);  
  32.         File dest = new File(destPath);  
  33.         //如果源文件不存在,抛出异常  
  34.         if(!src.exists()){  
  35.             throw new IOException("文件不存在!");  
  36.         }  
  37.         //如果目标文件父路径不存在,创建父路径  
  38.         if(!dest.getParentFile().exists()) {  
  39.             dest.getParentFile().mkdirs();  
  40.         }  
  41.         //实例化输入流和输出流  
  42.         InputStream is = new FileInputStream(src);  
  43.         OutputStream os = new FileOutputStream(dest);  
  44.         //定义缓冲字节数组,用来接收读取的内容  
  45.         byte buf[] = new byte[1024];  
  46.         int len = 0;  
  47.         while((len=is.read(buf))!=-1) {  
  48.             os.write(buf,0,len);  
  49.             os.flush();  
  50.         }  
  51.         //关闭流  
  52.         os.close();  
  53.         is.close();  
  54.     }  
  55. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值