我编写了一个将对象写入文件的方法。 我使用了泛型,因此也可以编写从 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/