Share on Google+Share on Google+

java write to a specific line

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

Advertisements

Posted on: September 22, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.