Java,用什么代替PrintStream来获取异常?
我正在网络驱动器上创建一个文件,然后向其中添加数据。有时写入该文件会失败。有没有一种好方法可以在每次将数据保存到文件之前检查文件是否可访问,或者是否可以在之后检查数据是否已保存?
编辑: 现在我在代码中使用带有 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 和 PrintStream 从不抛出 IOExceptions)
I am creating a file on a network drive and then adding data to it. Time to time writing to that file fails. Is there a good way of checking if the file is accessible before every time i save data to it or maybe is tehre a way checking afther to see if the data was saved?
EDIT:
Right now i am using try-catch block with PrintStream in my code:
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());
}
So might be the PrintStream the problem? (PrintWriter and PrintStream never throw IOExceptions)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将使用普通的 BufferedWriter 并根据需要自己添加换行符。
如果出现错误,正常的 FileOutputStream 操作应该抛出 IOException。
AFAIK,唯一的例外是 PrintWriter,它不会抛出异常。相反,您需要调用 checkError(),但它不会告诉您错误是什么或何时发生。
我建议您在这种情况下不要使用 PrintWriter。
I would use plain BufferedWriter and add the newlines myself as required.
Normal FileOutputStream operations should throw an IOException if there is an error.
AFAIK, The only exception is PrintWriter which does not throw an exception. Instead you need to call checkError() but it gives you no indication of what the error was or when it occurred.
I suggest you not use PrintWriter in this situation.
解决此问题的唯一合理方法是尝试写入文件,并以适当的方式处理任何产生的异常。由于网络的不可靠性质,几乎不可能事先知道 I/O 操作是否会成功。
The only reasonable way to address this is to try to write to the file, and handle any resulting exception in an appropriate manner. It's pretty much impossible to know beforehand whether an I/O operation is going to succeed, due to the unreliable nature of networks.