簡體   English   中英

循環檢查文件是否存在

[英]loop to check if a file exists

我有一個文件夾,它必須始終包含一個文件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。

嘗試使用 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);
}

然后您可以處理您的關鍵事件。

如果您必須使用 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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM