使用Java在文件里插入一行

在文件里增加一行的唯一方法就是读取原始文件,然后写入到一个临时文件,同时写入要插入的数据。然后删除原始文件,再把临时文件改名为原始文件名。

  1. package net.java2000.io;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.io.PrintWriter;  

  9. public class FileInsertRow {  
  10.   
  11.   public static void main(String args[]) {  
  12.     try {  
  13.       FileInsertRow j = new FileInsertRow();  
  14.       j.insertStringInFile(new File(args[0]), Integer.parseInt(args[1]), args[2]);  
  15.     } catch (Exception e) {  
  16.       e.printStackTrace();  
  17.     }  
  18.   }  
  19.   
  20.   /** 
  21.    * 在文件里面的指定行插入一行数据 
  22.    *  
  23.    * @param inFile 
  24.    *          文件 
  25.    * @param lineno 
  26.    *          行号 
  27.    * @param lineToBeInserted 
  28.    *          要插入的数据 
  29.    * @throws Exception 
  30.    *           IO操作引发的异常 
  31.    */  
  32.   public void insertStringInFile(File inFile, int lineno, String lineToBeInserted)  
  33.       throws Exception {  
  34.     // 临时文件  
  35.     File outFile = File.createTempFile("name"".tmp");  
  36.   
  37.     // 输入  
  38.     FileInputStream fis = new FileInputStream(inFile);  
  39.     BufferedReader in = new BufferedReader(new InputStreamReader(fis));  
  40.   
  41.     // 输出  
  42.     FileOutputStream fos = new FileOutputStream(outFile);  
  43.     PrintWriter out = new PrintWriter(fos);  
  44.   
  45.     // 保存一行数据  
  46.     String thisLine;  
  47.     // 行号从1开始  
  48.     int i = 1;  
  49.     while ((thisLine = in.readLine()) != null) {  
  50.       // 如果行号等于目标行,则输出要插入的数据  
  51.       if (i == lineno) {  
  52.         out.println(lineToBeInserted);  
  53.       }  
  54.       // 输出读取到的数据  
  55.       out.println(thisLine);  
  56.       // 行号增加  
  57.       i++;  
  58.     }  
  59.     out.flush();  
  60.     out.close();  
  61.     in.close();  
  62.   
  63.     // 删除原始文件  
  64.     inFile.delete();  
  65.     // 把临时文件改名为原文件名  
  66.     outFile.renameTo(inFile);  
  67.   }  
  68. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值