Как очистить / сбросить / открыть входной поток, чтобы его можно было использовать в 2 разных методах в Java? - PullRequest
2 голосов
/ 07 октября 2011

Вот код:

    package testpack;
    import java.io.*;

    public class InputStreamReadDemo {


        private void readByte() throws IOException {
            System.out.print("Enter the byte of data that you want to be read: ");        
            int a = System.in.read();
            System.out.println("The first byte of data that you inputted corresponds to the binary value "+Integer.toBinaryString(a)+" and to the integer value "+a+".");
            // tried writing System.in.close(); and System.in.reset();
        }
        private void readLine() throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter a line of text: ");
            String res = br.readLine();
            System.out.println("You entered the following line of text: "+res);
            // ... and tried writing br.close();
            // but that messes things up since the input stream gets closed and reset..
        }

        public static void main(String[] args) throws IOException {
            InputStreamReadDemo isrd = new InputStreamReadDemo();
            isrd.readByte();                                                // method 1
            isrd.readLine();                                                // method 2
        }
    }

Вот вывод, когда я запускаю это (и я вводю «Что-то», когда вызывается первый метод, второй метод по какой-то причине автоматически читает «omething» вместо того, чтобы позволить мне вводить снова…):

run:
Enter the byte of data that you want to be read: Something
The first byte of data that you inputted corresponds to the binary value 1010011 and to the integer value 83.
Enter a line of text: You entered the following line of text: omething
BUILD SUCCESSFUL (total time: 9 seconds)

1 Ответ

3 голосов
/ 07 октября 2011

Причина, по которой он выводит "omething", заключается в том, что при вызове readByte вы потребляете только первый байт вашего ввода. Затем readLine потребляет остаток байтов в потоке.

Попробуйте эту строку в конце вашего метода readByte: System.in.skip(System.in.available());

Это пропустит оставшиеся байты в вашем потоке ("omething"), оставляя ваш поток открытым, чтобы использовать ваш следующий ввод для readLine.

Обычно закрывать System.in или System.out не очень хорошая идея.

import java.io.*;

public class InputStreamReadDemo {


    private void readByte() throws IOException {
        System.out.print("Enter the byte of data that you want to be read: ");        
        int a = System.in.read();
        System.out.println("The first byte of data that you inputted corresponds to the binary value "+Integer.toBinaryString(a)+" and to the integer value "+a+".");
        System.in.skip(System.in.available());
    }
    private void readLine() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter a line of text: ");
        String res = br.readLine();
        System.out.println("You entered the following line of text: "+res);
        // ... and tried writing br.close();
        // but that messes things up since the input stream gets closed and reset..
    }

    public static void main(String[] args) throws IOException {
        InputStreamReadDemo isrd = new InputStreamReadDemo();
        isrd.readByte();                                                // method 1
        isrd.readLine();                                                // method 2
    }
}

Результаты:

$ java InputStreamReadDemo
Enter the byte of data that you want to be read: Something
The first byte of data that you inputted corresponds to the binary value 1010011 and to the integer value 83.
Enter a line of text: Another thing
You entered the following line of text: Another thing

ОБНОВЛЕНИЕ: Как мы уже говорили в чате, он работает из командной строки, но не в NetBeans. Должно быть что-то с IDE.

...