File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes trimming down a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "trimming down a string" Watch "trimming down a string" New topic

trimming down a string

Jeroen Nouws

Joined: Jul 14, 2011
Posts: 17
I got a byte[] from an xml stream that i want to print to the screen,
this is not really a problem but there's a lot of whitespace in the end and i want it out.
the byte[] is always different but here's an example of the output

as you can see a lot of whitespace :/

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
There are lots of things you could do.
If you get a zero-length line when reading from the file, you could simply ignore it.
If you get a line which is all whitespace, which you can easily find a regular expression for, again, you can ignore it.
You can match for whitespace at the end of the line with a similar regular expression and a line-end boundary match, and use the String.replace() or replaceAll() method on it.

I am sure there are lots of other things you can do. Anybody else got any ideas?

I am not convinced String#trim() is what you want, because it will take the leading whitespace out too, and you would lose your indentation.
Claudiu Chelemen
Ranch Hand

Joined: Mar 25, 2011
Posts: 74

Supposing that you've got a well formed xml in the byte[], I wouldn't bother formatting the xml myself, instead I would use some tool that is specialized on xml handing.

e.g. Maybe I would run it through an org.apache.xml.serialize.XMLSerializer along with the OutputFormat set accordingly.

One of the advantages would be that, in the future, if I get an xml with some other display issues (eg bad identing), the problem would be already solved.

I agree. Here's the link:
subject: trimming down a string
It's not a secret anymore!