简体   繁体   中英

why is my ByteArrayInputStream empty after creating it from any string?

Basically I'm using (in groovy ) the following construction:

InputStream in = new ByteArrayInputStream("one two three four".getBytes());

but then when I print its content:

println(in.text)

I see empty line. Why so? and how can I save those bytes in my InputStream?

Your original code gives me a compilation error in Groovy Console:

InputStream in = new ByteArrayInputStream("one two three four".getBytes());
println(in.text)

1 compilation error:

expecting EOF, found 'in' at line: 1, column: 13

in is a reserved word in Groovy. Changing it to inn all work well:

InputStream inn = new ByteArrayInputStream("one two three four".getBytes())
println(inn.text)

With this output:

one two three four

The bytes are in the InputStream , your just printing it wrong. Try converting the InputStream to a String with a Scanner , and then printing it.

Scanner s = new Scanner(in).useDelimeter("\\Z");
while (s.hasNext()) {
    System.out.print(s.next());
}

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