java - 异常实用写文件

标签 java

我编写了一个将对象写入文件的方法。 我使用了泛型,因此也可以编写从 Object 派生的对象(我也可以接受 Object 类型的参数,但这更清楚)。

public static <T extends Object> void write(T item,String path) 
throws FileNotFoundException,IOException
{
    ObjectOutputStream os;
    Object obj=item;
    os=new ObjectOutputStream(new FileOutputStream(path));
    os.writeObject(obj);
    os.close();
}

因此,疑问在于实用性:不处理异常而忽略它们是否正确?因为我还编写了该方法的第二个版本:

public static <T extends Object> void nothrow_write(T item,String path) 
{
    ObjectOutputStream os;
    Object obj=item;
    try
    {
        os=new ObjectOutputStream(new FileOutputStream(path));
        os.writeObject(obj);
        os.close();
    }
    catch(FileNotFoundException e)
    {
        System.out.println(e);
    }
    catch(IOException e)
    {
        System.out.println(e);      
    }
}

哪种方法更实用正确? 第一个问题是,如果抛出异常,流仍保持打开状态。

最佳答案

如果您愿意,您可以使用finally block 来确保流关闭,同时仍然抛出异常:

public static <T extends Object> void myMethod(T item,String path) throws FileNotFoundException,IOException
{
    ObjectOutputStream os;
    Object obj=item;
    try
    {
        os=new ObjectOutputStream(new FileOutputStream(path));
        os.writeObject(obj);
    }
    catch(FileNotFoundException e)
    {
        throw e; // Perhaps log the error before throwing
    }
    catch(IOException e)
    {
        throw e; // Perhaps log the error before throwing
    }
    finally 
    {
         // Close stream here
    }

}

关于java - 异常实用写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354599/

相关文章:

java - 通过对数字属性执行 ADD 操作来更新 DynamoDB

java - 如何减少桌面应用程序中的 hibernate 内存使用?

java - 创建链表的数组列表

java - 使用打洞通过 TCP 套接字在 android 中通信时出现连接拒绝错误

java - 如何在java中摆脱这个 "static method should be acessed in a static way"?

java - 如何修复最后一个表达式 : trial = trial/numtrials * 4? 中未定义的运算符

java - 在 Spring MVC 中捕获 Hibernate Validator 消息文本

java - 使用eclipse创建Web服务时出现404

java - 禁用 JTable 的特定行

java - 关于Spark的持久化机制