I am completing an assignment converting decimal to binary, hex & BCD. That part of it went fine and works as intended. We are supposed to send the output to a file. When I test the program using printf it looks good: nice orderly colums. When I use the format method of a Formatter object and send the output to a file it's a mess. The colums are gone. Even playing with WordWrap does not resolve it. I thought at first I neglected to put in a '\n' but I had not. How do I get the Formatter object to preserve the spacing I painstakingly set up via the printf approach? Is it even possible?
The maddening part is this isn't even a Java course. It's for my Assembly Language/Computer Hardware Organization class. We were given the option of doing it in Java or C++. My C++ is even rustier than my Java so I thought I was taking the easy way out. I checked the Java tutorial and didn't find much in regard to this.
Are you using System.out.printf()? What are you using as the format String to get your nice spacing?
I would have thought that you need to pass the File name to the Formatter constructor, then for each line, use myFormatter.format(formatString, arg0 . . . argn);
Don't use \n with a Formatter; put %n in the format String. You get better correspondence with the OS-specific line end like that.
Unlike a BufferedWriter/FileWriter, you cannot tell a Formatter to append to a File. At least I think so; I have never found how to do it.
Please try again; if that doesn't work please post some more details of your file-writing code.
Joined: Apr 17, 2006
Thanks Campbell, I'll try and get rid of the \n and replace with %n. I'm wondering if there may be some maximum amount a text file can take in terms of string length before the formatting is altered when it's copied.
Joined: Oct 13, 2005
There probably is a limit to the size of a text file, but it might be something like 2147483647 characters. You would do well to keep the individual lines shorter than 80 characters, then they will look good both on screen and on paper.
Joined: Apr 17, 2006
Thanks for the help, Campbell. You were spot on. Replacing \n with %n took care of the problem.