Java writes data to a TXT file (TXT has a fixed format)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.