[Solved] Line Numbers - Java Task (Files and Streams)

  

2
Topic starter

Write a program that reads a text file and inserts line numbers in front of each of its lines. The result should be written to another text file.

Read from 01_LinesIn.txt and compare your output against 01_LinesOut.txt, then read 02_LinesIn.txt and compare to its respctive output file and so on.

Examples:

line numbers task
1 Answer
1

The solution:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
public class Pr_02_LineNumbers {
    public static void main(String[] args) throws IOException {
        String source = "resources\\02_OddLinesIn.txt";
 
        try (BufferedReader bf = new BufferedReader(new FileReader(new File(source)))) {
            String readLine;
            int counter = 1;
            while ((readLine = bf.readLine()) != null) {
                System.out.printf("%d. %s%n", counter, readLine);
                counter++;
            }
        }
    }
}
Share: