java - 没有异常困惑的文件 I/O

标签 java file exception file-io

最好的使用方法是什么? 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/

相关文章:

java - 如何减去以前的键值(存储在数据库中)

java - 如何使用通用枚举实现 Action 监听器?

java - java中的构造函数引用是一种动态绑定(bind)吗?

Java/hibernate/JPA : cannot persist with compound key -> transient object

python - 异常必须派生自 BaseException

file - TYPO3 在 fileadmin 之外创建文件夹挂载

flash - Flash ActionScript 可以读写本地文件系统吗?

java.io.FileNotFoundException :/mnt/sdcard/1358731920220. jpg(没有这样的文件或目录)

java - 如何在 Java 异常消息中包含用户输入?

spring-mvc - Spring Boot RestController,关于错误状态响应体,错误消息为空