java write to a specific line


 

java write to a specific line

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

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();
}
}
}

Ads