使用Java在文件里插入一行

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

  1. package net.java2000.io;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.PrintWriter;
  8. /**
  9.  * 给文件增加一行数据。
  10.  * 
  11.  * @author 赵学庆,Java世纪网(java2000.net)
  12.  * 
  13.  */
  14. public class FileInsertRow {
  15.   public static void main(String args[]) {
  16.     try {
  17.       FileInsertRow j = new FileInsertRow();
  18.       j.insertStringInFile(new File(args[0]), Integer.parseInt(args[1]), args[2]);
  19.     } catch (Exception e) {
  20.       e.printStackTrace();
  21.     }
  22.   }
  23.   /**
  24.    * 在文件里面的指定行插入一行数据
  25.    * 
  26.    * @param inFile
  27.    *          文件
  28.    * @param lineno
  29.    *          行号
  30.    * @param lineToBeInserted
  31.    *          要插入的数据
  32.    * @throws Exception
  33.    *           IO操作引发的异常
  34.    */
  35.   public void insertStringInFile(File inFile, int lineno, String lineToBeInserted)
  36.       throws Exception {
  37.     // 临时文件
  38.     File outFile = File.createTempFile("name"".tmp");
  39.     // 输入
  40.     FileInputStream fis = new FileInputStream(inFile);
  41.     BufferedReader in = new BufferedReader(new InputStreamReader(fis));
  42.     // 输出
  43.     FileOutputStream fos = new FileOutputStream(outFile);
  44.     PrintWriter out = new PrintWriter(fos);
  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.     inFile.delete();
  64.     // 把临时文件改名为原文件名
  65.     outFile.renameTo(inFile);
  66.   }
  67. }











<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值