這個讀文件爲什麼不可以呢?

 

項目中有個讀Stream的問題,我用了最原始的辦法,發現當InputStream中是xml可以讀出,當是其他的時候就不可以了。雖然後來有了其他方案解決了,但是還是不知道原因,這裏貼出來,想知道大家的看法,謝謝.

 

 try {
     Assert.notNull(file);
     InputStream in = file.getFileContent().getInputStream();
     List<Byte> cache = new ArrayList<Byte>();
     byte data = (byte) in.read();
     while (data != -1) {
      cache.add(data);
      data = (byte) in.read();
     }
     if (in != null) {
      in.close();
     }
     byte[] cache2 = new byte[cache.size()];
     for (int i = 0; i < cache.size(); i++) {
      cache2[i] = cache.get(i);
     }
     System.out.println("cache2:  " + cache2.length);
     output.write(cache2);
    } finally {
     if (output != null) {
      output.close();
     }
    }

 

 

===>>

 

 

  try {
     Assert.notNull(file);
     InputStream in = file.getFileContent().getInputStream();
     byte[] cache2 = new byte[in.available()];
     in.read(cache2);
     output.write(cache2);
     if (in != null) {
      in.close();
     }
    } finally {
     if (output != null) {
      output.close();
     }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章