Java 如何检查是否正在读取文件

Java 如何检查是否正在读取文件,java,jasper-reports,Java,Jasper Reports,有人能告诉我是否可以检查文件是否正在读取。如果它正在被读取,那么我如何让我的程序等待,直到读取结束,以便它可以开始写入它 当我试图写入正在读取的文件时,出现以下错误: net.sf.jasperreports.engine.JRException: Error trying to export to file : ......(some errors not shown here) .... Caused by: java.io.FileNotFoundException: D:\serv

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

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

 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
net.sf.jasperreports.engine.jr异常:尝试导出到文件时出错:
…(此处未显示某些错误)。。。。
原因:java.io.FileNotFoundException:D:\servers\u installs\tomcat6\u 9494\webapps\testdoc\logs\xyz.pdf(该进程无法访问该文件,因为另一进程正在使用该文件)
在java.io.FileOutputStream.open(本机方法)
位于java.io.FileOutputStream。(未知源)
位于java.io.FileOutputStream。(未知源)
位于net.sf.jasperreports.engine.export.JRPdfExporter.exportReport(JRPdfExporter.java:305)
... 还有19个

您不必检查是否正在读取文件:

 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
  • 调用read函数

  • 调用write函数

  • 按该顺序调用函数将自动让程序先读取文件,然后再写入文件

    以下代码可能会有所帮助:

    try
    {
        //enter the code which is giving the specified error here.
    }
    catch(JRException e)
    {
          System.out.println("Jasper Exception.");
    }
    
    确保所有变量都已正确初始化。
    如果你能把你的代码贴在这里,那会很有帮助的

    我已经有一段时间没有使用Java了,但我相信您可以选择使用try-catch块。如果捕获到异常,这意味着写入失败,您可以继续尝试,直到成功。下面的示例可能是正确的Java代码,也可能不是。但是你应该了解大概的情况

    boolean worked = false;
    while (!worked && timeout<20)
    {
       try
       {
         // writing code here
    
         // set worked to true
         worked = true;
       }
       catch
       {
         // do nothing
       }
    }
    
    boolean=false;
    
    while(!worked&&timeout+1-这是正确的方法。请尝试执行您想执行的操作,如果出现异常,请进行处理(例如在本例中重试)。如果您输入特殊逻辑来检查文件是否可用,则可能会出现争用情况。您是否可以控制这两个程序?如果可以,您可以使用锁定文件或其他IPC来同步它们。否则,请按照Dalal的建议执行。我只能控制写入。我正在写入pdf文件。但是,其他人正在读取它。Dalal的解决方案看起来最好。我会试试。谢谢。@Harke,try-catch技术对你有用吗?我只能写入pdf文件。其他人会读取它,所以我无法控制它。现在我明白你所说的“如果文件正在读取”是什么意思了.在这种情况下,你必须检查一个文件是否打开;不幸的是,我不知道它到底是如何工作的,但我相信你可以通过谷歌搜索找到一个解释。