我正在网络驱动器上创建一个文件,然后向其中添加数据。向该文件写入失败的时间。有没有一种好的方法可以在每次保存数据之前检查文件是否可访问,或者是否有一种方法可以进一步检查数据是否被保存?
编辑:现在我在我的代码中使用带有PrintStream的try-catch块:
try
{
logfile = new File(new File(isic_log), "log_" + production);
//nasty workaround - we'll have a file the moment we assign an output stream to it
if (!logfile.exists())
{
prodrow = production;
}
out = new FileOutputStream(logfile.getPath(), logfile.exists());
p = new PrintStream(out);
if (prodrow != "")
{
p.println (prodrow);
}
p.println (chip_code + ":" + isic_number);
p.close();
}
catch (Exception e)
{
logger.info("Got exception while writing to isic production log: " + e.getMessage());
}那么,PrintStream可能是问题所在吗?(PrintWriter and PrintStream never throw IOExceptions)
发布于 2011-05-04 16:50:30
我会使用普通的BufferedWriter,并根据需要自己添加换行符。
如果出现错误,正常的FileOutputStream操作应该抛出IOException。
唯一的例外是PrintWriter,它不会抛出异常。相反,您需要调用checkError(),但它没有给出错误是什么或何时发生的提示。
我建议你在这种情况下不要使用PrintWriter。
发布于 2011-05-04 16:49:40
解决此问题的唯一合理方法是尝试写入文件,并以适当的方式处理任何产生的异常。由于网络的不可靠特性,几乎不可能预先知道I/O操作是否会成功。
https://stackoverflow.com/questions/5880816
复制相似问题