JAVA 读文件使用装饰者模式的代码示例
时间: 2024-02-17 15:00:02 浏览: 31
下面是一个使用装饰者模式读取文件的Java代码示例:
```
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class FileReader {
private Reader reader;
public FileReader(File file) throws IOException {
FileInputStream fileInputStream = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(fileInputStream));
}
public String read() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
int character;
while ((character = reader.read()) != -1) {
stringBuilder.append((char) character);
}
return stringBuilder.toString();
}
public void close() throws IOException {
reader.close();
}
}
```
在上述代码中,我们使用了BufferedReader和InputStreamReader两个装饰者,将FileInputStream转换为Reader对象,以便更方便地读取文件内容。同时,我们还可以通过添加其他的装饰者,如GZIPInputStream等,实现更高级的文件读取功能。
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)