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