Java 的讀寫問題

          A common question when using the IO classes is why this block of code does not work:


          File aFile = new File("input.data");
          InputStream is = new FileInputStream(aFile);
          byte[] data = new byte[aFile.length()];
          is.read(data);

          The results can be puzzling. If the input file is an image it may be mangled or not display at all. Binary or text data may be incomplete. This is because Read Doesn't Do What You Think It Does. A quick glance at the Java API for java.io.InputStream gives us the following information:


          public int read(byte[] b) throws IOException

          Reads some number of bytes from the input stream and stores them
          into the buffer array b. The number of bytes actually read is returned as an integer. . .

          The documentation states that read reads "some number" of bytes. It is not guaranteed to fill the byte array. The number of bytes read is returned by the read method. One should use this return value to make sure that he is receiving the data which he expects. A correct usage of read() would be to read chunks of a file and collect them in a buffer like so:


          ByteArrayOutputStream buffer = new ByteArrayOutputStream();
          File aFile = new File("input.data");
          InputStream is = new FileInputStream(aFile);
          byte[] temp = new byte[1024];
          int read;

          while((read = is.read(temp)) > 0){
             buffer.write(temp, 0, read);
          }
                     
          byte[] data = buffer.toByteArray();
          // process the data array . . .

          posted on 2007-11-01 17:28 劉錚 閱讀(227) 評論(0)  編輯  收藏 所屬分類: JAVA General

          <2025年5月>
          27282930123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          導航

          統計

          留言簿(1)

          文章分類(141)

          文章檔案(147)

          搜索

          最新評論

          主站蜘蛛池模板: 孟津县| 延安市| 略阳县| 米脂县| 巴南区| 鄂伦春自治旗| 郯城县| 固始县| 自贡市| 桑日县| 柏乡县| 凤凰县| 阿图什市| 卢氏县| 勃利县| 怀安县| 宜兴市| 广河县| 定安县| 阳谷县| 南昌市| 安徽省| 冀州市| 北海市| 鸡东县| 盖州市| 札达县| 饶阳县| 星座| 北碚区| 洪雅县| 乐业县| 榕江县| 兴城市| 威海市| 灯塔市| 庄浪县| 荃湾区| 依安县| 磐安县| 临海市|