settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Line Numbers - Java Task (Files and Streams)

+13 votes

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:

Input.txt

Output.txt

Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
Where civil blood makes civil hands unclean.
From forth the fatal loins of these two foes
A pair of star-cross'd lovers take their life;
Whose misadventured piteous overthrows
Do with their death bury their parents' strife.

  1. Two households, both alike in dignity,
  2. In fair Verona, where we lay our scene,
  3. From ancient grudge break to new mutiny,
  4. Where civil blood makes civil hands unclean.
  5. From forth the fatal loins of these two foes
  6. A pair of star-cross'd lovers take their life;
  7. Whose misadventured piteous overthrows
  8. Do with their death bury their parents' strife.

 

 

 

asked in Java category by user ak47seo

1 Answer

+1 vote
 
Best answer

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++;
            }
        }
    }
}

 

answered by user andrew
selected by user golearnweb
...