简体   繁体   中英

Reading the content from an inputstream using scanner multiple times is not behaving as expected

I am using the following code to read content from an input stream.

@Test
public void testGetStreamContent(){
        InputStream is = new ByteArrayInputStream("Hello World!!".getBytes());
        System.out.println(getStreamContent(is));
        System.out.println("Printed once");
        System.out.println(getStreamContent(is));
}

public static String getStreamContent(InputStream is) {
    Scanner s = null;
    try {
        s = new Scanner(is);
        s.useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    } finally {
        if (s != null){
            s.close();
        }
    }
}

I'm expecting the output to contain Hello World!! twice, but it is not returning the text the second time. Following is the only output.

Hello World!!
Printed once

I have tried resetting the scanner by using s.reset(). But that is also not working.

Try this instead

    ByteArrayInputStream is = new ByteArrayInputStream("Hello World!!".getBytes());
    if(is.markSupported()){
        is.mark("Hello World!!".length());
    }
    System.out.println(getStreamContent(is));
    is.reset();
    System.out.println("Printed once");
    System.out.println(getStreamContent(is));

Things to note: I changed the variable type from InputStream to the instance type so I could call the methods specific to that type ( mark , reset and markSupported ). That allows the stream to point back to the last marked position.

Calling a reset on inputstream is working for me.

public static String getStreamContent(InputStream is) throws IOException {
    if(is == null)
        return "";
    is.reset();
    Scanner s = null;
    try {
        s = new Scanner(is);
        s.reset();
        s.useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    } finally {
        if (s != null){
            s.close();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM