将字节流转换为字符缓冲流,并进行换行读写内容
时间: 2023-12-03 14:42:23 浏览: 31
可以使用 InputStreamReader 将字节流转换为字符流,并使用 BufferedReader 进行缓冲读取和写入,同时使用 System.getProperty("line.separator") 获取系统换行符进行换行操作。以下是示例代码:
```java
import java.io.*;
public class ByteToCharExample {
public static void main(String[] args) {
FileInputStream fis = null;
BufferedReader br = null;
try {
// 读取字节流
fis = new FileInputStream("test.txt");
// 将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(fis);
// 使用缓冲读取
br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
// 写入到控制台,每行后面添加系统换行符
System.out.println(line + System.getProperty("line.separator"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在上述示例代码中,我们使用 try-with-resources 语法简化了资源关闭操作。同时,我们使用了 System.getProperty("line.separator") 方法获取系统换行符并将每行读取的内容末尾添加换行符后输出到控制台。
相关推荐
![](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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)