How to write value into text file based on column in java?

I try to create a file where I can append values based on columns. So that each value for each column will always start from a specific column. For eg, column 1 to 10 is the name and column 11 to 20 is id. value for name will always start column 1 and value for id will always start from column 11. My code is not suitable because the value of ikeeps increasing. I also try the 1: Write CSV file column-by-column but it’s different from my objective

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < 10000; i++) {
        list.add("Name-1" + i + "21412900092974RHB0218" + "");
    }

    try {
        PrintStream output = new PrintStream("output.txt");
        String listString = "";
        for (String s : list)
        {
            output.print(listString += s + "n");
        }
        
        output.close();
    } catch (Exception e) {
        e.getStackTrace();
    }
}

Answer

All you need is to ensure the different parts are of the targeted size. E.g. you have an issue that your numbers are of different length. However, Java has a method that will allow you to write into a String a number with prepended symbols, so that the length is always fixed:

String.format("%04d", i)

Will print sequentially:

0000
0001
0002
...
0010
0011

you can also have a space prepended: String.format("%4d", i) or even appended after String.format("%-4d", i)

Leave a Reply

Your email address will not be published. Required fields are marked *