---
title: "使用Java在文件里插入一行"
author: "java2000.net"
date: "2008-09-14T20:23:00Z"
tags: []
slug: "java"
draft: false
lastmod: "2008-09-14T20:23:00Z"
id: 241832
url: "https://java2000-net.iteye.com/blog/241832"
---

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

01. package net.java2000.io;
02. import java.io.BufferedReader;
03. import java.io.File;
04. import java.io.FileInputStream;
05. import java.io.FileOutputStream;
06. import java.io.InputStreamReader;
07. import java.io.PrintWriter;
08. /\**
09. * 给文件增加一行数据。
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. }

&lt;script type="text/javascript"&gt; &lt;/script&gt; &lt;script src="http://pagead2.googlesyndication.com/pagead/show\_ads.js" type="text/javascript"&gt; &lt;/script&gt;