0

I'm having trouble around reading from a text file into a String in Java. I have a text file (created in Eclipse, if that matters) that contains a short amount of text -- approximately 98 characters. Reading that file to a String via several methods results in a String that is quite a bit longer -- 1621 characters. All but the relevant 98 are invisible in the debugger/console.

I've tried the following methods to load the String:

apache commons-io:

FileUtils.readFileToString(new File(path));

FileUtils.readFileToString(new File(path), "UTF-8");

byte[] b = FileUtils.readFileToByteArray(new File(path);
new String(b, "UTF-8");

byte[] b = FileUtils.readFileToByteArray(new File(path);
Charset.defaultCharset().decode(ByteBuffer.wrap(bytes)).toString();

NIO:

new String(Files.readAllBytes(path);

And so on.

Is there a method to strip away these control chars? Is there a way to read files to strings that doesn't have this issue?


As noted in the comments below, this behavior is due to a corrupted(?) file generated by Eclipse. I'd still be interested in hearing any strategies for trimming away control characters from Strings, though!

3
  • If it's an actual text file, there shouldn't be any "control characters", so I might check all assumptions first. For me, eclipse text files are just that, text. Commented Jan 6, 2014 at 22:38
  • 1
    have you tried opening it with a hex editor?
    – ug_
    Commented Jan 6, 2014 at 22:44
  • @DaveNewton, good suggestion. I think it is a fluke. Some combination of using the Eclipse New > Other > General > file dialog, naming it a .csv file, and having LibreOffice as my default csv editor seems to cause it. Creating the file differently makes the problem go away. Guess I'll submit an Eclipse bug report!
    – AbGator
    Commented Jan 6, 2014 at 22:53

2 Answers 2

4

If you want to strip out all non-printable characters, try this

str = str.replaceAll("[^\\p{Graph}\n\r\t ]", "");

The regex matches all "invisible" characters, except ones we want to keep; in this case newline chars, tabs and spaces.

\p{Graph} is a POSIX character class for all printable/visible characters. To negate a POSIX character class, we can use capital P, ie P{Graph} (all non-printable/invisible characters), however we need to not exclude newlines etc, so we need [^\\p{Graph}\n\r\t] .

7
  • This did work -- though it has the regrettable consequence of stripping away some useful chars like carriage returns and spaces. But it's in the right direction.
    – AbGator
    Commented Jan 8, 2014 at 0:46
  • Well, that's easily fixed: Just add the other characters you want to keep to the character class. I've put in line feeds, carriage returns, tabs and spaces - you can add others ass needed, just follow the example. See edited answer.
    – Bohemian
    Commented Jan 8, 2014 at 1:12
  • @Omid A ? probably means it's a visible charaxcter, but notepad doesn't have a code point for it. This question was about removing invisible characters.
    – Bohemian
    Commented Nov 9, 2014 at 15:01
  • @Bohemian I'm use string.trim().replace("\ufeff", "").
    – Omid Omidi
    Commented Nov 10, 2014 at 16:12
  • 1
    @lordvidex see additional explanation in the answer
    – Bohemian
    Commented Jun 30, 2021 at 2:33
0

Read it line by line into a StringBuilder, and then convert it to a String:

StringBuilder sb = new StringBuilder();
BufferedReader file = new BufferedReader(new FileReader(fileName));
while (true)
{
    String line = file.readLine();
    if (line == null)
        break;
    sb.append(line+"\n");
}
file.close();
return sb.toString();
1
  • As I noted above, this behavior is a fluke.. but I tried your suggestion anyway. Under those same circumstances, it has the same results as the other methods. i.e. it gives more than a thousand invisible chars.
    – AbGator
    Commented Jan 6, 2014 at 22:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.