2012-07-06 25 views
1

我正在嘗試使用FilterInputStream,但我無法使其工作。 如果我編程FilterReader一切順利:FilterInputStream不執行

import java.io.*; 

class Filter extends FilterReader { 
    Filter(Reader in) { 
    super(in); 
    } 

    public int read() throws IOException { 
    return 'A'; 
    } 
} 

public class TestFilter { 
    public static void main(String[] args) throws IOException { 
    Reader in = new Filter(new InputStreamReader(System.in)); 
    System.out.println((char)in.read()); 
    } 
} 

執行是一個

,但如果我用FiterInputStream,執行單元中的閱讀:

import java.io.*; 

class Filter extends FilterInputStream { 
    Filter(InputStream in) { 
    super(in); 
    } 

    public int read() throws IOException { 
    return 'A'; 
    } 
} 

public class TestFilter { 
    public static void main(String[] args) throws IOException { 
    Reader in = new InputStreamReader(new Filter(System.in)); 
    System.out.println((char)in.read()); 
    } 
} 
+0

適合我!我執行了代碼(第二個),按'+'輸入,並在控制檯中顯示相同的字符。 – Sujay 2012-07-06 13:28:28

回答

2

在第一個代碼,你的讀者是:

new Filter(new InputStreamReader(System.in)); 

及其read方法是一個喲u必須重寫:

public int read() throws IOException { 
    return 'A'; 
} 

在第二個代碼,你的讀者是:

new InputStreamReader(new Filter(System.in)); 

,而不是用你的過濾器的方法read。讀卡器會在System.in上等待,因此您必須鍵入某些內容(+ ENTER)才能讀取某些內容。

+1

由於@ user1496621說InputStreamReader.read應該委託給Filter.read,但實際上它委託給Filter.read(byte [],int,int),它不會被覆蓋 – francesc 2012-07-06 14:49:13

0

在你的第二個TestFilter更換

Reader in = new InputStreamReader(new Filter(System.in)); 

隨着

InputStream in = new Filter(System.in); 

這將在您創建發送 「A」 至System.out類執行Filter.read()

2

在第一種情況下,.read()直接調用Filter.read()方法。 在第二種情況下,.read()調用InputStreamReader.read()。
現在我們可能期望它將調用委託給Filter.read()。但InputStreamReader.read()的實現做了別的 - 我不明白它在做什麼。
但最終FilterInputStream.read(byte [],int,int)方法被調用,它等待用戶輸入。因此,爲了獲得您期望的行爲 - 我想 - 我們需要重寫此讀取方法 - 如下所示。

import java.io. *;

class Filter extends FilterInputStream { 
    Filter(InputStream in) { 
    super(in); 
    } 

    public int read() throws IOException { 
    return 'A'; 
    } 

    @Override 
    public int read(byte[] b, int off, int len) throws IOException { 
     if(len == 0) { 
      return 0; 
     } 
     b[off] = (byte) read(); 
     return 1; 
    } 

} 

public class TestFilter { 
    public static void main(String[] args) throws IOException { 
    Reader in = new InputStreamReader(new Filter(System.in)); 
    System.out.println((char)in.read()); 
    } 
} 
+0

您是對的,謝謝! – francesc 2012-07-06 14:46:06