簡體   English   中英

讀取后InputStream不清除

[英]InputStream not clearing after being read

我有以下代碼:

public class Interface {    
    public void exec(){            
        Scanner scanner = null;
        Integer count = 0;

        while( count < 4 ){               
            _inputStream.read();
            scanner = new Scanner( _inputStream );
            String inputLine = scanner.nextLine();
            _inputStream.reset();
            System.out.println( inputLine );
        }
        scanner.close();
    }

    public void setInputStream( InputStream inputStream ){
        _inputStream = inputStream;
    }
}

我正在嘗試使用以下代碼進行測試:

public void testInterface() {
    Interface ui = new Interface();
    ui.exec();

    ui.setInputStream( new ByteArrayInputStream( "This is the first prompt".getBytes( Charset.defaultCharset() ) ) );   
    ui.setInputStream( new ByteArrayInputStream( "This is the second prompt".getBytes( Charset.defaultCharset() ) ) );  
    ui.setInputStream( new ByteArrayInputStream( "This is the third prompt".getBytes( Charset.defaultCharset() ) ) );           
    ui.setInputStream( new ByteArrayInputStream( "This is the fourth prompt".getBytes( Charset.defaultCharset() ) ) );
}

我想得到的輸出是

This is the first input
This is the second input
This is the third input
This is the fourth input

但我實際上得到的是

his is the first input
his is the first input
his is the first input
his is the first input

至少就我所知,這個_inputStream是在循環的每次迭代中都沒有清除_inputStream ,這意味着read()函數將立即返回,而不是等待新的數據流。 我會在每次閱讀后重置流,因此我不確定為什么會這樣。

如何修改代碼,使_inputStream.read()在每次循環運行時都等待用戶輸入?

錯誤,每次調用setInputStream()之后都調用exec()嗎?

這可能不是您的真實代碼。

在方法exec()您正在調用_inputStream.read() ,該方法正在阻塞。 但這並不意味着在此階段執行不執行exec()! 這不像C#協程。

因此實際上_inputStream.read()是針對在_inputStream中其他位置分配的InputStream的任何實例調用的,它將在您有機會調用ui.setInputStream( new ByteArrayInputStream( .....

因此,您在同一InputStream中讀取了4次,並在讀取之后對其進行了重置。 因此,您具有相同的4行輸出。

同樣,重設方法會將流重設回設置了最后一個標記的位置或開始處,但不會取出其中的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM