How to insert line number in file using Java


In this example, we are going to show to add Line Number in a file using java program. Here we are going to read a simple text file (QuickBrownFox.txt) and write the all the content with the line number in a new text file(NewQuickBrownFox.txt).

QuickBrownFox.txt
"The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. 
It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet.
Owing to its brevity and coherence, it has become widely known.
InsertLineNumExp.java
package org.websparrow.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

public class InsertLineNumExp {

	public static void main(String[] args) {
		int ctr = 0;
		try {

			BufferedReader bufferedReader = new BufferedReader(new FileReader("QuickBrownFox.txt"));
			PrintWriter printWriter = new PrintWriter(new FileWriter("NewQuickBrownFox.txt"));
			
			String str;

			while ((str = bufferedReader.readLine()) != null) {

				ctr++;
				printWriter.println(ctr + ". " + str);
				System.out.println(ctr + ". " + str);
				Thread.sleep(500);
			}
			
			printWriter.close();
			bufferedReader.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Output:

NewQuickBrownFox.txt
1. "The quick brown fox jumps over the lazy dog" is an English-language pangram—a phrase that contains all of the letters of the alphabet. 
2. It is commonly used for touch-typing practice. It is also used to test typewriters and computer keyboards, show fonts, and other applications involving all of the letters in the English alphabet.
3. Owing to its brevity and coherence, it has become widely known.

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.