最好的使用方法是什么? FileOutputStream
而不会弄乱我的代码。
例如以下代码:
我需要做的是:
FileOutputStream fOut = new FileOutputStream(file);
while(!Thread.currentThread().isInterrupted()){
fOut.write(data);
//other code
}
但是如果我加上异常处理就很乱了。例如,我想到了以下内容:
private FileOutputStream openStream(String file){
try{
return new FileOutputStream(file);
}
catch(FileNotFoundException e){
return null;
}
}
但这让逻辑变得奇怪。我的意思是当我关闭流时,例如在另一种方法等
有什么方法可以让代码更清晰
最佳答案
像这样的包装器怎么样:
public class StreamWrapper {
private FileOutputStream fileOutputStream;
public FileOutputStream open(String file) {
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// Define action
}
return fileOutputStream;
}
public void close() {
try {
fileOutputStream.close();
} catch (IOException e) {
// Define action
}
}
}
像这样使用它:
StreamWrapper wrapper = new StreamWrapper();
FileOutputStream fOut = wrapper.open("file");
// something
wrapper.close();
关于java - 没有异常困惑的文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14952566/