
Read a text file and precede the line with the line number and write it to another new text file.
For example if you create a file Source.txt which has the following contents: Hello there I am supposed to have line numbers preceding me. Is it there ?
shall be written to Destination.txt as: 1. Hello there 2. I am supposed to have line numbers preceding me. 3. Is it there?

Hi Friend,
Try the following code:
import java.io.*;
class FileExample{
public static void main(String[] args)throws Exception{
BufferedWriter bw=new BufferedWriter(new FileWriter("C:/destination.txt",true));
LineNumberReader ln = new LineNumberReader(new FileReader(new File("C:/hello.txt")));
String line = "";
while ((line = ln.readLine()) != null){
System.out.println("Line: " + ln. getLineNumber() + ": " + line);
bw.write("Line: " + ln. getLineNumber() + ": " + line);
bw.newLine();
}
bw.close();
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.