user7407723
user7407723

Reputation: 11

java Error IOException

This code gives me an error when I take more than one data by keyboard in the same application, it gives an IOException error;

gives error when leaving the do while

I don't know why he makes this kind of mistake.

 public static String datoString() {
// Entorno:
    BufferedReader br;

    String frase;
    boolean esCorrecto;
    //Algoritmo
    frase=null;
    br = new BufferedReader(new InputStreamReader(System.in));
    try {
        do {

            System.out.println("Introduce una cadena");
            frase = br.readLine();
            esCorrecto = true;


        } while (!esCorrecto);

    } catch (IOException ioe) {
        System.err.println("Error I/O");
    }
    try {
        br.close();
    } catch (IOException ioe2) {
        ioe2.printStackTrace();
    }//Fin try


    return frase;

}

Upvotes: 0

Views: 124

Answers (1)

Antoniossss
Antoniossss

Reputation: 32550

By doing this

 br.close();

You are actually doing this

System.in.close();

Because BufferedReader closes underlying stream.

This makes System.in stream no longer available for use. What you need to do, is to do a little trick to prevend System.in from closing. To do that, you can use following wrapper

public class ShieldedInputStream extends InputStream {

    InputStream source;

    public ShieldedInputStream(InputStream source) {
        this.source = source;
    }

    @Override
    public int read() throws IOException {
        return source.read();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return source.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return source.read(b, off, len);
    }

    @Override
    public long skip(long n) throws IOException {
        return source.skip(n);
    }

    @Override
    public int available() throws IOException {
        return source.available();
    }

    @Override
    public void close() throws IOException {
//        source.close(); // We dont awant to close it!
    }

    @Override
    public void mark(int readlimit) {
        source.mark(readlimit);
    }

    @Override
    public void reset() throws IOException {
        source.reset();
    }

    @Override
    public boolean markSupported() {
        return source.markSupported();
    }
}

And use it like this

br = new BufferedReader(new InputStreamReader(new ShieldedInputStream(System.in)));

This way you will prevent System.in from closing, but still allowing you to free resources by closing BufferedReader

Upvotes: 2

Related Questions