Anton Kahwaji
Anton Kahwaji

Reputation: 467

What's the difference between reading from a string and reading from an inputstream?

in java I can do this

String sstream1 =
        "as aasds 2 33\n" +
        "this\n" +
        "2.23\n";
InputStream stream = new ByteArrayInputStream(sstream1.getBytes());
Scanner cin = new Scanner(stream);
Scanner cin2 = new Scanner(sstream1);
String x1 = cin.next();
String x2 = cin.next();
int x3 = cin.nextInt();
int x4 = cin.nextInt();
String x5 = cin.next();
double x6 = cin.nextDouble();
Stream.of(x1, x2, x3, x4, x5, x6).forEach(o -> System.out.println(o));
x1 = cin2.next();
x2 = cin2.next();
x3 = cin2.nextInt();
x4 = cin2.nextInt();
x5 = cin2.next();
x6 = cin2.nextDouble();
Stream.of(x1, x2, x3, x4, x5, x6).forEach(o -> System.out.println(o));

I still get the same result

as
aasds
2
33
this
2.23
as
aasds
2
33
this
2.23

so I'd like to know what's the difference between using these two methods, are there any pros and cons for each one because the second is much easier and simpler, and are there any other better ways to achieve this?

Upvotes: 1

Views: 318

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

Straight forward, best:

String sstream1 = ... // May contain Greek, Chinese, emoji, math symbols
Scanner cin2 = new Scanner(sstream1);

Default platform encoding, back and forth conversion to the Unicode String. Could go wrong on special characters. Not cross-platform.

InputStream stream = new ByteArrayInputStream(sstream1.getBytes());
Scanner cin = new Scanner(stream);

Explicit, cross-platform, but twice a conversion.

InputStream stream = new ByteArrayInputStream(sstream1.getBytes(StandardCharsets.UTF_8));
Scanner cin = new Scanner(stream, "UTF-8");

Note that System.out uses the default platform charset too, which makes the test code unusable. But scanning will only work with the first, or last code (with Unicode's UTF-8) for all Unicode.

Upvotes: 0

Procrastinator
Procrastinator

Reputation: 2664

An InputStream is the raw method of getting information from a resource. It grabs the data byte by byte without performing any kind of translations. If you are reading image data, or any binary file, this is the stream to use.

On the other hand, when you use String then it is for the sequence of characters. You can use different character encoding styles and decoding with the character sequences. So, in case if you are reading just the text data or characters then it is okay if you use String but say, if you are using an image or any binary file then you have to take care of further processing and encodings.

Upvotes: 2

Related Questions