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

时间:2015-03-12 11:43:04

标签: java inputstream java.util.scanner

我使用以下代码从输入流中读取内容。

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

我期待输出包含Hello World !!两次,但它没有第二次返回文本。以下是唯一的输出。

Hello World!!
Printed once

我尝试过使用s.reset()重置扫描仪。但这也行不通。

2 个答案:

答案 0 :(得分:1)

试试这个

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

需要注意的事项:我将变量类型从InputStream更改为实例类型,因此我可以调用特定于该类型的方法(markresetmarkSupported )。这允许流指向最后标记的位置。

答案 1 :(得分:0)

在输入流上调用重置对我有用。

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