java读取文件并修改文件内容
时间: 2023-12-03 09:37:55 浏览: 69
Java读取文件并修改文件内容可以通过使用FileReader和FileWriter类来实现。具体步骤如下:
1. 使用FileReader类的对象读取文件内容,可以使用read方法获取数据。
2. 对文件内容进行修改。
3. 使用FileWriter类的对象将修改后的内容写入文件中,可以使用write方法写入数据,最后使用flush方法刷新缓冲区并关闭流。
下面是一个示例代码,演示如何读取文件并修改文件内容:
```
import java.io.*;
public class FileModify {
public static void main(String[] args) {
try {
// 读取文件
String path = "file.txt";
String content = FileReader(path);
// 修改文件内容
content = content.replace("Hello", "Hi");
// 写入文件
FileWriter(path, content, false);
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取文件
public static String FileReader(String path) throws IOException {
String FileDateString;
File file = new File(path);
FileReader FR = new FileReader(file);
char[] FileData = new char[(int) file.length()];
FR.read(FileData);
FileDateString = new String(FileData);
return FileDateString;
}
// 写入文件
public static void FileWriter(String path, String content, boolean append) throws IOException {
FileWriter fw = new FileWriter(new File(path), append);
fw.write(content);
fw.flush();
fw.close();
}
}
```