Insert a row in a file using Java

Source: Internet
Author: User

The only way

To add a row to a file is to read the original file and then write to a temporary file, while writing the data to be inserted. Then delete the original file, and then rename the temporary file to the original file name.

Package Net.java2000.io
Import java.io.BufferedReader;
import java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
/**
* Adds one row of data to the file.
*
* @author Zhaoqing, Java Century Network (java2000.net)
*
*/
public class Fileinsertrow {
public static void main (    String args[]) {
try {
Fileinsertrow j = new Fileinsertrow ();
J.insertstringinfile (New File (Args[0]), Integer.parseint (args[1), args[2]);   
} catch (Exception e) {
E.printstacktrace ();

}
/**
* Inserts a row of data in the specified row in the file
*
* @param inFile
* File
* @param lineno
* Line Number
* @param linetobeinserted
* The data to be inserted
* @throws Exception
* The exception thrown by the IO operation
*/
Public void Insertstringinfile (file inFile, int lineno, String linetobeinserted)
throws Exception {
//temp file
F ile outfile = File.createtemPFile ("Name", ". tmp");   
//input
FileInputStream fis = new FileInputStream (inFile);
BufferedReader in = new BufferedReader (new InputStreamReader (FIS));   
//Output
FileOutputStream fos = new FileOutputStream (outfile);
PrintWriter out = new PrintWriter (FOS);   
//Save one row of data
String Thisline
  The line number starts with 1
int i = 1;
while ((Thisline = In.readline ())!= null) {
//If the line number equals the target row, output the data to be inserted
if (i = = Lineno) {
Out.println (l inetobeinserted);    
}
//output read Data
Out.println (thisline);
  Line number increases
i++;
}
Out.flush ();
Out.close ();
In.close ();   
//Delete original file
Infile.delete ();
 Rename the temporary file to the original filename
Outfile.renameto (inFile);
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.