2012-05-24 19 views
1
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
public class BufferedInputOutputStreamExample 
{ 
    public static void main(String[] args) { 
     try{ 
     BufferedInputStreamExample bisx=new BufferedInputStreamExample(); 
     BufferedInputStream bis=bisx.inputMethod(); 

     BufferedOutputStreamExample bosx=new BufferedOutputStreamExample(); 
     bosx.outputMethod(bis); 
     } 
     catch(FileNotFoundException fnf) 
     { 
      System.out.println("Sorry--------File not exists"); 
     } 
     catch(IOException io) 
     { 
      System.out.println("IOException ---:"+io.getMessage()); 
     } 


    } 
} 
class BufferedInputStreamExample 
{ 
    BufferedInputStream bis=null; 
    BufferedInputStream inputMethod()throws FileNotFoundException,IOException 
    { 
      FileInputStream fin=new FileInputStream("C:/e-SDK-4.1-win32-x86_64 (1)/RahulExample/src/Test.java"); 
      bis=new BufferedInputStream(fin); 
      int c; 
      while((c=bis.read())!=-1) 
       System.out.print((char)c); 
      System.out.println(); 

     return bis; 
    } 
} 
class BufferedOutputStreamExample 
{ 
    BufferedOutputStream bos=null; 
    int outputMethod(BufferedInputStream bis)throws IOException,FileNotFoundException 
    { 
     bos=new BufferedOutputStream(new FileOutputStream("C:/varun.txt")); 

     int c; 

     while((c=bis.read())!=-1){ 
      bos.write(c); 
     } 
     bis.close(); 
     bos.close(); 
     System.out.println("File created............."); 
     return 1; 
    } 
} 
在這個計劃中,我們使用的BufferedInputStream,當我想用​​的BufferedOutputStream,其創建文件中寫入Test.java文件中varun.txt文件中的內容,但不寫在VARUN任何東西從文件中讀取內容

.txt。如果我們將Test.java中的內容寫入varun.txt而不讀取它,則創建文件並寫入兩者。爲什麼這樣做就是這樣做的。在BufferedInputStream和BufferedOutputStream類中,爲什麼在寫入之前,讀取不好.......?

+0

plz給答案。 –

回答

1

當您撥打bisx.inputMethod()時,您正在閱讀流以打印其內容。事情是,你不想這樣做只是。讀取流會消耗它,所以你要返回的流已經到了最後,沒有什麼可讀的。

如果要打印出文件的所有內容,然後將其全部寫入其他文件,那麼這是兩個單獨的操作。根據文件的大小,它需要兩次讀取文件 - 使用兩個不同的輸入流 - 或緩存整個內存。

相反,如果你只是想顯示你複製它(它看起來像這裏的真正目標)的文件的內容,你有幾個值得選擇...

  • 你可以已將outputMethod打印到數據,因爲它正在寫入輸出文件。這可能是短期內最簡單的解決方法。當然,您也可以刪除讀取流的inputMethod中的代碼。

  • 你可以FilterInputStreamFilterOutputStream定義流,每當它讀取或寫入數據(分別),做別的東西與它。它可以,例如...

    • 打印的數據System.out非常簡單,但僵化。我越考慮它...... meh。

    • 將數據複製到另一個任意輸出流。這會更靈活;例如,你可以發送到日誌文件或其他東西。並且它需要額外的代碼很少,因此它通常會在這個大減價部門贏得勝利。

    • 觸發其他對象可以訂閱的事件。這可以給你幾乎無限的靈活性(因爲用戶不再需要關心流),但也可能會更復雜一些。 (你基本上需要添加一個事件/訂閱API。)對於像這樣的一個小項目來說,這通常是過分的。

    請注意,如果你走這條路線,你應該考慮重構的東西,以便對象的構造函數採取一個流而不是創建一個。這樣,main可以決定輸出是否發生以及去向,其他對象甚至不必關心。他們可以完成他們的工作,將流視爲普通的舊InputStream和OutputStreams,並且您傳入的流決定發生什麼。

(順便說一句:爲了集中在主要問題上,我半忽略了一個事實,你是「解碼」通過轉換成char這可能無法真實再現的內容。文件,除非你知道內容是ASCII字符的事實,我假設輸出是一個調試的東西,所以這不值得長時間的咆哮......但要知道,在一般情況下,它可能會導致問題)

相關問題