My program is reading a text file and doing actions based on the text. But the first line of the text is problematic. Apparently it starts with "". This is messing my startsWith()
checks.
To understand the problem I've used this code :
System.out.println(thisLine
+ " -- First char : (" + thisLine.charAt(0)
+ ") - starts with ! : "
+ thisLine.startsWith("!"));
String thisLine
is the first line in the text file.
it writes this to the console :
! use ! to add comments. Lines starting with ! are not read. -- First char : () - starts with ! : false
Why is this happening and how do I fix this? I want it to realize that the line starts with "!" not ""
Collecting mine and others' comments into one answer for posterity, your string probably contains unprintable control characters. Try
System.out.println( (int)thisLine.charAt(0) )
to print out their numerical code or
my_string.replaceAll("\\p{C}", "?");
to replace the control characters with '?'.
System.out.println( (int)thisLine.charAt(0) )
printed 65279
for you which would be the Unicode code point for a zero-width space, not unprintable but effectively invisible on output. (See Why is  appearing in my HTML?).
Either remove the extra whitespace character from the file, remove all control characters from the string (my_string.replaceAll("\\p{C}", "");
) or use @arvind's answer and trim the string (thisLine = thisLine.trim();
) before reading so it contains no whitespace at the very beginning or the very end of the string.
EDIT: Notepad won't show most 'special' characters. If you want to edit the file try a hex editor or a more advanced version of notepad such as Notepad++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With