java使用io流读写txt文件
时间: 2023-11-02 11:05:19 浏览: 70
可以使用java.io包中的FileReader和FileWriter类,或者使用java.nio包中的FileChannel和ByteBuffer类来读写txt文件。我们可以通过创建File对象指定文件路径,然后使用FileReader或FileChannel来读取文件中的内容,使用FileWriter或FileChannel来写入内容到txt文件中。例如:
使用FileReader和FileWriter:
```
File file = new File("path/to/txt/file.txt");
try {
FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file);
// 读取文件
int c;
while ((c = fileReader.read()) != -1) {
// 处理读取到的字符
}
// 写入文件
fileWriter.write("content to write");
fileWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
```
使用FileChannel和ByteBuffer:
```
File file = new File("path/to/txt/file.txt");
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
// 读取文件
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = fileChannel.read(buf);
while (bytesRead != -1) {
buf.flip();
// 处理读取到的内容
buf.clear();
bytesRead = fileChannel.read(buf);
}
// 写入文件
String str = "content to write";
ByteBuffer writeBuf = ByteBuffer.wrap(str.getBytes());
fileChannel.write(writeBuf);
} catch (IOException e) {
e.printStackTrace();
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)