-1

I am trying to print some text line by line using the PrintWriter

I have tried various combinations such as

   1. mystring.trim() before println(mystring) 
   2. not using println and using \n instead

but my output file always ends up with a "trailing white space" at the end of each line. How can I remove that?

toffee.beanns
  • 435
  • 9
  • 17
  • [FYI](http://stackoverflow.com/q/7506771/2749470) – Bhargav Modi Mar 27 '15 at 10:18
  • I am not sure if I understand your question but if "trailing white space" is line separator like `\n` or `\r` or `\r\n` then you should probably read documentation of `println` and `print` methods. – Pshemo Mar 27 '15 at 11:56
  • @Pshemo Yeah, you got that right, I managed to resolve the issue by putting \r thanks – toffee.beanns Mar 27 '15 at 14:05

2 Answers2

1

String.trim() doesn't modify the string - it returns a new one with the spaces removed; this is because Strings in Java are immutable i.e. cannot be changed. You don't show your code, but I'm guessing this is the problem with your trim approach.

String mystring = "Hello   ";
mystring.trim();  // creates a new string, but doesn't assign it to anything
System.out.println(mystring);  // prints the original String unchanged

Instead, you can do:

String mystring = "Hello   ";
System.out.println(mystring.trim());  // prints the trimmed String
DNA
  • 42,007
  • 12
  • 107
  • 146
0

Type something along the lines of this:

println(mystring.trim())

That should work fine.

:)

Chronicler
  • 59
  • 3