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

解决方案 »

  1.   

    skyyoung(路人甲) 太厉害了,怎么什么都懂啊?呵呵。
      

  2.   

    使用这种办法读取的每一行都不包括回车换行符.写到新文件里时全部都在一行中了,
    这种效果并不好!
    有种RandomAccessFile的类你知道怎么用吗?这种好像可以对文件直接进行读写.不需要
    临时文件!但是我没用过.
      

  3.   

    可用以下代码
    private BufferedReader FileRead;   
    private FileOutputStream OutFile; //读文件
    FileRead=new BufferedReader(new InputStreamReader(new FileInputStream(FileName)));
    while(FileRead.readLine()!=null){
    } //写文件
    OutFile = new FileOutputStream(T_File);
    Writer out = new OutputStreamWriter(OutFile);
    out.write(tempString);
    out.close();
      

  4.   

    我觉得这里要用RamdenAccessFile类比较好一点