---
title: "java 修改文件的多行内容"
author: "风流情不留"
date: "2015-01-21T10:08:47Z"
tags: []
categories: ["移动开发"]
slug: "java"
draft: false
lastmod: "2015-01-21T10:23:16Z"
id: 2177906
url: "https://171151394.iteye.com/blog/2177906"
---

1、将文件内容一行一行的读出来   
2、在每读一行的时候，判断是否以a或b开始，如果是则进行处理，然后写到缓冲对象。如果不是则直接写入缓冲对象中   
3、将缓冲对象中的内容回写到文件中 

 

01. import java.io.BufferedReader;
02. import java.io.BufferedWriter;
03. import java.io.FileReader;
04. import java.io.FileWriter;
05. import java.io.IOException;
06. /\**
07. * 修改文件
08. \*/
09. public class FileModify {
10. /\**
11. * 读取文件内容
12. \*
13. * @param filePath
14. * @return
15. \*/
16. public String read(String filePath) {
17. BufferedReader br = null;
18. String line = null;
19. StringBuffer buf = new StringBuffer();
20. try {
21. // 根据文件路径创建缓冲输入流
22. br = new BufferedReader(new FileReader(filePath));
23. // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中
24. while ((line = br.readLine()) != null) {
25. // 此处根据实际需要修改某些行的内容
26. if (line.startsWith("a")) {
27. buf.append("start with a").append("\\n");
28. }
29. // 如果不用修改, 则按原来的内容回写
30. else {
31. buf.append(line).append("\\n");
32. }
33. }
34. } catch (Exception e) {
35. e.printStackTrace();
36. } finally {
37. // 关闭流
38. if (br != null) {
39. try {
40. br.close();
41. } catch (IOException e) {
42. br = null;
43. }
44. }
45. }
46. return buf.toString();
47. }
48. /\**
49. * 将内容回写到文件中
50. \*
51. * @param filePath
52. * @param content
53. \*/
54. public void write(String filePath, String content) {
55. BufferedWriter bw = null;
56. try {
57. // 根据文件路径创建缓冲输出流
58. bw = new BufferedWriter(new FileWriter(filePath));
59. // 将内容写入文件中
60. bw.write(content);
61. } catch (Exception e) {
62. e.printStackTrace();
63. } finally {
64. // 关闭流
65. if (bw != null) {
66. try {
67. bw.close();
68. } catch (IOException e) {
69. bw = null;
70. }
71. }
72. }
73. }
74. /\**
75. * 主方法
76. \*/
77. public static void main(String\[] args) {
78. String filePath = "C:/file.txt"; // 文件路径
79. FileModify obj = new FileModify();
80. obj.write(filePath, obj.read(filePath)); // 读取修改文件
81. }
82. }