java实现文件内容的读取与写入
时间: 2023-09-14 17:07:47 浏览: 90
文件的读取与写入是Java中非常常见的操作,可以使用Java中的FileReader和FileWriter类来实现。
文件内容的读取:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
File file = new File("file.txt");
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
文件内容的写入:
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
File file = new File("file.txt");
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello World!");
bufferedWriter.newLine();
bufferedWriter.write("This is a test.");
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这里使用了BufferedReader和BufferedWriter类,可以提高读写文件的效率。同时注意要在程序结束时关闭文件流,以释放资源。
阅读全文