简体   繁体   English

多次使用扫描仪从输入流读取内容的行为与预期不符

[英]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!! 我希望输出包含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(). 我尝试使用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 ). 注意事项:我将变量类型从InputStream更改为实例类型,因此可以调用特定于该类型的方法( markresetmarkSupported )。 That allows the stream to point back to the last marked position. 这样可以使流指向最后标记的位置。

Calling a reset on inputstream is working for me. 在inputstream上调用reset对我来说是有效的。

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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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