如何等待文件创建 [英] How to wait on file creation

查看:95
本文介绍了如何等待文件创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况如下: 我有一个Java程序,从此启动了一个perl脚本. Perl脚本正在生成一个文件,Java应该在该文件上继续工作. 到目前为止,我已经设置了

My situation is as following: I got a Java program, wich starts a perl script. The Perl script is generating a file, on which Java should continue working. As by now, i had set a

Thread.sleep(3000);

让Java等待文件完成. 我一直在寻找一种更优雅的方法来让Java检查文件是否存在,然后继续.我最后一次尝试是

to let Java wait for the file to be finished. I was looking for an more elegant way to let Java check if the file exists and continue then. My last try was

Boolean waitforfile = true;  
while(waitforfile){
       File f = new File(pathtofile);
       if(f.exists() && !f.isDirectory()) { waitforfile=false; }
       } 

但是那会让我陷入一个永无止境的循环中. 还有其他方法吗?

But that one will get me stuck in a never ending loop. Is there any way else to do it?

更新: 在建议上,尝试过,处理,WaitFor(); 在

Update : On Suggestion, tried, process,WaitFor(); In

    public static String syscall(String call){
    String out = "";
    try {
    String line;
    Process p = Runtime.getRuntime().exec(call);
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
      out=out+"\n"+line;
    }
    input.close();
    p.waitFor();
    } catch (Exception e) {
        System.out.println(e);
    }

    return out;
}

这个人并没有等待我的perl进程被关闭.

This one did not wait on my perl process to be closed.

推荐答案

更好的方法是将文件写入临时文件名,例如myscript.pl.tmp,并在完成后重命名.由于重命名是原子的,因此您不会看到它处于不完整的状态.

A better way is to write the file to a temporary file name like myscript.pl.tmp and rename it when you are finished. As rename is atomic, you won't see it in an incomplete state.

顺便说一句,您可以使用WatchService在文件出现时得到通知. 监视目录中的更改

BTW You can use the WatchService to be notified when a file appears. Watching a Directory for Changes

这篇关于如何等待文件创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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