黑马程序员技术交流社区

标题: 字节输入输出流 [打印本页]

作者: chenguoyu520    时间: 2015-10-3 14:48
标题: 字节输入输出流
  1. import java.io.*;
  2. class InputAndOutputDemo {

  3.         public static void main(String[] args) {
  4.                 //创建文件对象
  5.                 File source=new File("E:\\超能陆战队.rmvb");
  6.                 File target=new File("E:\\超能陆战队.rmvb");
  7.                 if(!target.exists()){//如果目标文件不存在,则创建
  8.                         try {
  9.                                 target.createNewFile();
  10.                         } catch (IOException e) {
  11.                                 e.printStackTrace();
  12.                         }
  13.                 }
  14.                
  15.                 FileInputStream in=null;
  16.                
  17.                 FileOutputStream out=null;
  18.                 try {
  19.                         //创建字节输入流对象
  20.                         in=new FileInputStream(source);
  21.                         //创建字节输出流对象
  22.                         out=new FileOutputStream(target);
  23.                         byte[] buf=new byte[1024];//定义字节数组
  24.                         int len;
  25.                         while((len=in.read(buf))!= -1){
  26.                                 out.write(buf, 0, len);
  27.                         }
  28.                         out.flush();//刷新
  29.                 } catch (Exception e) {
  30.                         e.printStackTrace();
  31.                 }finally{//关闭资源
  32.                         if(in !=null){
  33.                                 try {
  34.                                         in.close();
  35.                                 } catch (IOException e) {
  36.                                         e.printStackTrace();
  37.                                 }
  38.                         }
  39.                         if(out!=null){
  40.                                 try {
  41.                                         out.close();
  42.                                 } catch (IOException e) {
  43.                                         e.printStackTrace();
  44.                                 }
  45.                         }
  46.                 }
  47.                
  48.         }

  49. }
复制代码





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