循环检查文件是否存在

时间:2018-11-13 12:45:19

标签: java file loops

我有一个文件夹,该文件夹必须始终包含一个文件 config8 ,如果在该文件夹中创建了一个新文件,则旧文件将被删除并由具有相同名称的新文件替换。 config8

我写这段代码

       File file1 = new File("/home/olfa/Bureau/config/config8");
       File file2 = new File("/home/olfa/Bureau/config/config9");
      while (file2.exists())
      {
          file1.delete();
          file2.renameTo(file1); }
      }
    serverConnection = new ServerConnection("/home/olfa/Bureau/config/config8");

我需要添加一个循环以每次检查是否创建config9。

2 个答案:

答案 0 :(得分:2)

尝试运行WatchService,而不是循环。

基本上,您将监视特定目录中的更改,然后您可以对此更改做出反应。

https://docs.oracle.com/javase/tutorial/essential/io/notification.html

例如:

import static java.nio.file.StandardWatchEventKinds.*;

WatchService watcher = FileSystems.getDefault().newWatchService();

Path dir = ...;
try {
    WatchKey key = dir.register(watcher,
                       ENTRY_CREATE,
                       ENTRY_DELETE,
                       ENTRY_MODIFY);
} catch (IOException x) {
System.err.println(x);
}

然后您可以处理关键事件。

答案 1 :(得分:0)

如果必须使用Java 1.6解决此任务,则可以使用https://commons.apache.org/proper/commons-vfs/,版本2.1。

以下是将所有传入的配置文件移动到“ config8”的示例:

import org.apache.commons.vfs2.*;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;

import java.io.File;

public class ConfigWatcher {
    private static final String configDirName = "target/config";
    private static final String configName = "config8";
    private static final String absoluteConfigName = new File(configDirName + File.separator + configName).getAbsolutePath();
    private FileSystemManager manager = null;
    FileObject configDir = null;
    private FileObject configFile = null;
    private FileChangeEvent lastEvent = null;

    public void watchConfig() throws Exception {
        manager = VFS.getManager();

        DefaultFileMonitor fm = new DefaultFileMonitor(new ConfigFileListener());
        configFile = manager.resolveFile(absoluteConfigName);
        configDir = manager.resolveFile(new File(configDirName).getAbsolutePath());
        fm.setDelay(1000);
        fm.addFile(configDir);
        fm.start();
    }

    class ConfigFileListener implements FileListener {
        public void fileCreated(FileChangeEvent fileChangeEvent) throws Exception {
            FileObject latestConfigFile = fileChangeEvent.getFile();
            String fileBaseName = fileChangeEvent.getFile().getName().getBaseName();
            if (!configName.endsWith(fileBaseName) && !fileChangeEvent.equals(lastEvent)) {
                System.out.println("new config detected - move config");
                latestConfigFile.moveTo(configFile);
            }
            lastEvent = fileChangeEvent;
        }

        public void fileChanged(FileChangeEvent fileChangeEvent) {
        }

        public void fileDeleted(FileChangeEvent fileChangeEvent) {
        }
    }


    public static void main(String[] args) throws Exception {
        final ConfigWatcher configWatcher = new ConfigWatcher();
        configWatcher.watchConfig();
        while (true) {
            Thread.sleep(1000);
        }
    }
}