如何检查是否正在读取文件 [英] How to check if a file is being read

查看:74
本文介绍了如何检查是否正在读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我是否可以检查文件是否正在读取.如果正在读取它,那么我该如何等待程序结束,直到读取结束,以便它可以开始写入程序中.

Could someone tell me whether it is possible to check if a file is being read. If it is being read then how do I make my program wait, till the reading is over so that it can begin writing into it.

当我尝试写入正在读取的文件时,出现以下错误:

I got the following error when I tried to write into a file that was being read:

 net.sf.jasperreports.engine.JRException: Error trying to export to file : 
......(some errors not shown here) ....
 Caused by: java.io.FileNotFoundException: D:\servers_installs\tomcat6_9494\webapps\testdoc\logs\xyz.pdf (The process cannot access the file because it is being used by another process)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at net.sf.jasperreports.engine.export.JRPdfExporter.exportReport(JRPdfExporter.java:305)
... 19 more

推荐答案

我已经有一段时间没有使用Java了,但是我相信您有一个选择是使用try catch块.如果捕获到异常,则表示写入失败,您可以继续尝试直到其生效.这是一个示例,该示例可能是正确的Java代码,也可能不是.但是您应该了解一般的想法.

I haven't used Java in a while, but one option I believe you have is to use try catch blocks. If an exception is caught, that means that writing failed, and you can keep trying again until it works. Here's an example that may or may not be correct Java code. But you should get the general idea.

boolean worked = false;
while (!worked && timeout<20)
{
   try
   {
     // writing code here

     // set worked to true
     worked = true;
   }
   catch
   {
     // do nothing
   }
}

确保它在单独的线程中运行.而且还要超时,以防万一还有另一个问题阻止写操作发生.希望有帮助.

Make sure this is running in a separate thread. And also time it out in case there's another issue that's preventing the write from happening. Hope that helps.

这篇关于如何检查是否正在读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆