1

I try to send string to my InputStream:

String _source = "123";
InputStream in = new ByteArrayInputStream(_source.getBytes("UTF-8"));
tempLab2.readR(in);
            
String _source2 = "321";
in.read(_source2.getBytes());
_myClass.readR(in);

When I create new ByteArrayInputStream and set _source as an argument, then everything works well. My method readR does not wait any \n or EOF charapters and reads 123.

Please enter R:

R: 123

readR method:

public void readR(InputStream inpSteram) {
    Scanner tScanner = new Scanner(inpSteram);
    System.out.println("Please enter R:");
    _R = tScanner.nextDouble();
    System.out.println("R: " + _R);
}

But if I send _source2 with in.read(_source2.getBytes()) so my Scanner is waiting and I see only

Please enter R:

Any ideas?

0

4 Answers 4

5

The line

in.read(_source2.getBytes());

does not add new info to the inputstream, instead it empties it, if there would have been more data. So the inputstream is exhausted.

You just need to create a new inputstream before the next call to readR. So:

String _source2 = "321";
in = new ByteArrayInputStream(_source2.getBytes("UTF-8"));
_myClass.readR(in);
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any way without creating a new ByteArrayInputStream?
No. Once you create a ByteArrayInputStream you cannot feed it with new bytes. You could change readR to accept a String and create the inputstream inside the method.
2

Your code doesn't make sense:

String _source2 = "321";
in.read(_source2.getBytes());

in.read() reads bytes from in, and stores what it has read in the byte array passed as argument. So basically, the above code creates a three bytes-long array, fills it with 3 bytes, and then tries to read bytes from the input stream and fills the 3-bytes-long byte array with the result.

1 Comment

Okey, but you did not answer how to fix it.
0

Don't use an InputStream for working with characters, use a Reader.

Also, in your second example, you are not doing what you think you are doing. you are not adding the _source2 bytes to the input stream. you are instead attempting to re-use the original bytes from the original InputStream, which is now empty.

Comments

0

It's not entirely obvious what you're after here, but when using the Scanner class, you can simply send a string straight to it like so:

Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();

And so on.. This is assuming, of course, that you're taking input from the console.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.