Rob
Rob

Reputation: 1065

Java adds spaces when reading in a line?

So I'm at my wit's end with this program. I'm reading in from a text file in Java. Barring everything that I do with the string once I have it, this is the bare minimum code to be shown.

            while ((lineIn = myReader.readLine()) != null) {
                System.out.println("LineIn: \""+lineIn+"\"");
                System.out.println("Length: "+lineIn.length());
            }

What it prints out, however, is very strange indeed. The line should read:

001 2014/06/09 09:40:24 0.000

But this is what I get:

LineIn: "�2�6�1�8� �2�0�1�4�/�0�7�/�1�0� �2�3�:�1�5�:�0�3� �0�.�0�0�0�" Length: 61

On Stack Overflow it actually shows up fine. You may be able to copy and paste the "LineIn: etc" into your address bar and see there are little invisible spaces in the numbering. I have no idea why those are there, what they are, and where Java is getting them from. Opening the document it's sourced from in a simple text editor shows no such spacing, and copy+pasting from the text editor into the browser address bar has no superfluous spacing either. It's very peculiar and I hope someone can offer insight. I'm pulling out my hair here.

Upvotes: 2

Views: 124

Answers (3)

Jerry101
Jerry101

Reputation: 13377

It looks like you're reading UTF-16 data as if it had an 8-bit encoding.

If you construct a java.io.InputStreamReader, you can specify the input text charset such as "UTF-16".

Upvotes: 4

Anti Veeranna
Anti Veeranna

Reputation: 11583

Java certainly is not doing that, it might be UTF-16 encoded file. Can you upload the file or a small part of it somewhere?

Upvotes: 2

SamTebbs33
SamTebbs33

Reputation: 5647

It could be due to the formatting and encoding that your reader is using, try using Scanner instead.

Upvotes: 4

Related Questions