Search code examples
javaio

How to add line number with trailing 0s to a .txt file?


I have a program which reads from a file and creates an error report which is a copy of said file, but the idea is that the error report will also include line number at the start of each line and the type of error that occurred at the end.

So for example, inputFile.txt contains:

This is the first line 
This is the second line

My program creates inputFile-errorReport.txt, which should look like this:

00001 This is the first line
00002 This is the second line

The max line number is 99999, how can I achieve this? I can copy the file to create the error report, but I don't know how to append info to each line start (or wherever I want) and much less how to count the lines with trailing 0s.


Solution

  • You can try this.

    for(int lineNumber = 0; lineNumber<10; lineNumber++) {
                System.out.printf("%05d%n", lineNumber);
            }
    

    Output:

    00000 00001 00002 00003 00004 00005 00006 00007 00008 00009