Home Tutorial Java Core java write to a specific line

 
 

Share on Google+Share on Google+
java write to a specific line
Posted on: September 22, 2012 at 12:00 AM
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();
}
}
}
Advertisement

Related Tags for java write to a specific line:


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.

Posted on: September 22, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com