The only way to insert a line in a text file is to read the original file and write the content in a temporary file with the new line inserted. Then we erase the original file and rename the temporary file to the original name.

In this example, you need to supply 3 arguments : the filename, a line number and the string to be inserted at the line number specified.

  java jINSERT test.out 9 "hello world"

will insert the string "hello world" at line number 9 in the file "test.out". Of course you need more error checking...

[JDK1.1]

 import java.io.*;

 public class jINSERT {
   public static void main(String args[]){
     try {
       jINSERT j = new jINSERT();
       j.insertStringInFile
          (new File(args[0]),Integer.parseInt(args[1]), args[2]);
       }
     catch (Exception e) {
       e.printStackTrace();
       }
     }

   public void insertStringInFile(File inFile, int lineno, String lineToBeInserted) 
       throws Exception {
     // temp file
     File outFile = new File("$$$$$$$$.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);

     String thisLine = "";
     int i =1;
     while ((thisLine = in.readLine()) != null) {
       if(i == lineno) out.println(lineToBeInserted);
       out.println(thisLine);
       i++;
       }
    out.flush();
    out.close();
    in.close();
    
    inFile.delete();
    outFile.renameTo(inFile);
  }
}