-2

I have this list of array string that I want to write in a file, but in a manner that there will be no space between them and no return to line. So, I tried to use a StringBuilder to that to make it all one unified string. However, I still get some random spaces between.

Here is the code I have:

FileWriter writer = new FileWriter("output.txt"); 
for (int i =0; i < MainClass.NUM_OF_SPLITS; i++){
    StringBuilder sb1 = new StringBuilder();
    StringBuilder sb2 = new StringBuilder();

    for (String s : MainClass.allSplits.get(i).blocks)
    {
        sb2.append(s);
    }
    sb1.append(sb2);
    writer.write(sb1.toString());
}
writer.close(); 

and here is the content of the Output File. The weird caraters are due to the fact that most of my strings are encrypted. Here's the results I get:

results

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
rima101
  • 43
  • 1
  • 7
  • 3
    How is an encrypted mass of random characters remotely useful to us? We don't even know what should and shouldn't be there. I'm not psychic, along with every user here other than Jon Skeet. – nanofarad Aug 13 '13 at 13:34
  • That looks fine to me. If you write binary some of them will randomly be `\n` BTW Don't mix text like Writer and StringBuiler with binary or you will lead to confusion esp as your character encoding is likely to mangle your bytes – Peter Lawrey Aug 13 '13 at 14:13

3 Answers3

1

Try using :

String example = value.replaceAll("\\s","");

This will replace all whitespace characters with an empty string. A whitespace character is:

[ \t\n\x0B\f\r]

According to this tutorial by Sun.

Also here's the doc for String.replaceAll

William Morrison
  • 10,953
  • 2
  • 31
  • 48
0
String output = input.replaceAll("\\s", "");

this deletes all whitespaces, tabs, linebreaks from the inputstring and returns the result to the outputstring

Joris W
  • 517
  • 3
  • 16
0

you can also remove newlines using

String output = input.replaceAll("(\\r|\\n)", "");

making a possible 1 line solution

String output = input.replaceAll("(\\r|\\n|\\s)", "");