2012-04-12 60 views
-1

如何將InputStreamReader轉換爲InputStream?我有一個InputStream其中包含一些字符串和字節數據,我想解析它。所以我把我的InputStream換成BufferedReader。然後我讀了3行。之後,我想按原樣獲取其餘數據(字節)。但是如果我試圖得到它沒有任何反應。 代碼片段:將InputStreamReader轉換爲InputStream

BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8")); 

       String endOfData = br.readLine(); 
       String contentDisposition = br.readLine(); 
       String contentType = br.readLine();  

       file = new File(filename); 
       if(file.exists()) file.delete(); 
       file.createNewFile(); 
       FileOutputStream fos = new FileOutputStream(file);     

       byte[] data = new byte[8192];  
       int len = 0;  

       while (-1 != (len = is.read(data)))  
       {     
        fos.write(data, 0, len); 
        Log.e("len", len+""); 
       }  
fos.flush(); 
fos.close(); 
is.close(); 

該文件是空的。如果我不包裝InputStream它工作正常,但我需要讀取3行並將其刪除。 謝謝。

回答

0

如果你想混合文本和字節數據,你應該使用OutputStream.writeUTF寫出這3行,這樣一個單一的InputStream將能夠檢索你需要的所有數據。

-2

要正確混合字節和字符輸入是非常困難的,特別是一旦你開始將緩衝的閱讀器/流投入混合。我建議你選擇一個並堅持下去(根據需要將字節轉換爲字符串;注意編碼!)或將整個事物包裝在ZipOutputStream中,以便可以有多個具有不同內容的邏輯「文件」。

-1

看看commons-io的ReaderInputStream:這有點笨拙,但你可以用它包裝BufferedReader並再次將它作爲輸入流讀取。

相關問題