阳光VIP

少壮不努力,老大徒伤悲。平日弗用功,自到临期悔。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

FileInputStream和FileOutputStream

Posted on 2012-02-12 19:41  阳光VIP  阅读(209)  评论(0编辑  收藏  举报
java 代码
  1. public class FileStreamDemo {   
  2.   
  3.     public static void main(String[] args) {   
  4.   
  5.         try {   
  6.   
  7.             byte[] buffer = new byte[1024];   
  8.   
  9.             // 来源文件   
  10.   
  11.             FileInputStream fileInputStream =   
  12.   
  13.                 new FileInputStream(new File(args[0]));   
  14.   
  15.             // 目的文件   
  16.   
  17.             FileOutputStream fileOutputStream =   
  18.   
  19.                 new FileOutputStream(new File(args[1]));   
  20.   
  21.             // available()可取得未读取的数据长度   
  22.   
  23.             System.out.println("复制文件:" +   
  24.   
  25.                     fileInputStream.available() + "字节");   
  26.   
  27.               
  28.   
  29.             while(true) {   
  30.   
  31.                 if(fileInputStream.available() < 1024) {   
  32.   
  33.                     // 剩余的数据比1024字节少   
  34.   
  35.                     // 一位一位读出再写入目的文件   
  36.   
  37.                     int remain = -1;   
  38.   
  39.                     while((remain = fileInputStream.read())   
  40.   
  41.                                            != -1) {   
  42.   
  43.                         fileOutputStream.write(remain);   
  44.   
  45.                     }   
  46.   
  47.                     break;   
  48.   
  49.                 }   
  50.   
  51.                 else {   
  52.   
  53.                     // 从来源文件读取数据至缓冲区   
  54.   
  55.                     fileInputStream.read(buffer);   
  56.   
  57.                     // 将数组数据写入目的文件   
  58.   
  59.                     fileOutputStream.write(buffer);   
  60.   
  61.                 }   
  62.   
  63.             }   
  64.   
  65.             // 关闭流   
  66.   
  67.             fileInputStream.close();   
  68.   
  69.             fileOutputStream.close();   
  70.   
  71.             System.out.println("复制完成");   
  72.   
  73.         }   
  74.   
  75.         catch(ArrayIndexOutOfBoundsException e) {   
  76.   
  77.             System.out.println(   
  78.   
  79.                       "using: java FileStreamDemo src des");   
  80.   
  81.             e.printStackTrace();   
  82.   
  83.         }   
  84.   
  85.         catch(IOException e) {   
  86.   
  87.             e.printStackTrace();   
  88.   
  89.         }   
  90.   
  91.     }   
  92.   
  93. }   
  94.   
使用available(),然后读int而不是byte[].如果不使用read()和write(int)的方法,会将多出的byte[]写入目标文件。