my question is related to my previous question (How to display data from txt file in specific format).
I was wondering if it is possible at the first place, to store data on txt file in specific format rather than store it first and then retreived it again and display it in specific format?
e.g. instead of store data on txt file like this
Jessica Walking 20 minutes Matthew Run 10 minutes
I wanted to store it in txt file in this format
Jessica Walking 20 minutes Matthew Run 10 minutes
If you want to write records of fixed length you can use the String.[format][1] method
This will create a table with 20 characters in each field. You can readup on the syntax here
[1]: http://java.sun.com/javase/6/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...)
Regarding your comment to adeel's answer:
First, don't call "
new PrintStream(fout)
" everytime you print something. Do this:Or simply:
Edit
In response to your comment:
If this is a problem, it sounds like you are trying to store them in the manner you want to display them. I had assumed you were trying to store them in a way that would be easy to parse programmatically. If you want to store them displayed in columns, I'd suggest padding with spaces rather than tabs.
If you know that all the columns are going to be less than, say, 30 characters wide, you could do something like this with printf:
That syntax can look quite byzantine if you're not used to it.. basiclly each "%30s" means pad the string argument so that it is at least 30 characters wide. Your result won't look right if any of the values are 30 or more characters wide. If you can't know ahead of time, you'll have to loop through the values in each column to determine how wide the columns need to be.
There is no problem with storing data this way. All you need to do is write out the values and delimit them with a tab character "\t"
You need to "handcode" your formatting. Best way to do this would be to wrap your file-accessing code somewhere, and create something like: