Home Tutorial Java Core java write to a specific line

 
 

java write to a specific line
Posted on: September 22, 2012 at 12:00 AM
In this tutorial, you will learn how to write at specific line in text file.

java write to a specific line

In this tutorial, you will learn how to write at specific line in text file.

Java provides java.io package to perform file operations. Here, we are going to write the text to the specific line of the text file. In the given example, we have used LineNumberReader class to keeps track of line numbers. It seek to the desired position in the file using the method setLineNumber() and insert the text there.

Example:

import java.io.*;

public class WriteAtSpecificLine {
public static void main(String[] args) {
String line = "";
int lineNo;
try{
File f=new File("c:/file.txt");
FileWriter fw = new FileWriter(f,true);
BufferedWriter bw = new BufferedWriter(fw);
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
lnr.setLineNumber(4);
for(int i=1;i<lnr.getLineNumber();i++){
bw.newLine();
}
bw.write("Hello World");
bw.close();
lnr.close();
} 
catch (IOException e) {
e.printStackTrace();
}
}
}

Related Tags for java write to a specific line:


Ask Questions?

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.