Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java adds spaces when reading in a line?

Tags:

java

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.

like image 859
Rob Avatar asked Aug 24 '26 08:08

Rob


1 Answers

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".

like image 132
Jerry101 Avatar answered Aug 25 '26 22:08

Jerry101



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!