Java writes data to a TXT file, which should be a simple matter for people who have learned Java I/O, but if you want to write the data in a fixed format to a TXT file, you need some tricks.
Here is a simple example for reference:
For example, I want to write the data in the following way:
1 | 2 | 3 | 4
5 | 6 | 8 | 9
It may seem simple, because each data represents a different length, or it can be coded differently, and everything you see as simple is not so easy to implement. Each vertical line and the vertical line below him must be the same.
The process of writing data is no longer presented here, and the point is that each column can have the same width of data:
public string Formatstr (string str, int length) { str = " " +STR; int strLen = Str.getbytes (). length; if (StrLen < length) { int temp = Length-strlen; for (int i = 0; i < temp; i++) { str + = ", |"; } } return str; }
Let's start by explaining the effect of this method: for the parameter str, if his byte length is less than the size of the parameter, it is padded with a space.
To do so, there is a problem, is how to determine how long length is appropriate?
If the data is found from the database, take the maximum length of this field in the database. If you read from a file, it is best to traverse the entire file to get the maximum length of each field.
Finally, the output stream of Str returned by the method is written to the file, and Out.write (LineSeparator) is used for line break.
Java writes data to a TXT file (TXT has a fixed format)