loop to check if a file exists












-2















I have a folder that must contain always one file config8, and if a new file is created in this folder the old file is deleted and replaced by the new file with the same name config8.



I write this code



       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");


I need to add a loop to check everytime if config9 is created.










share|improve this question


















  • 1





    Your opening paragraph implies if any new file is created in the folder. Your concluding remark is if only config9 is created. What is the exact requirement?

    – KevinO
    Nov 13 '18 at 12:55











  • Your code is very misleadingly laid-out, since you have a closing brace at the end of file2.renameTo(file1); }

    – khelwood
    Nov 13 '18 at 12:56











  • I just want to check if config9 is created in every time and thank you for your remark

    – olfa abdalah
    Nov 13 '18 at 12:58
















-2















I have a folder that must contain always one file config8, and if a new file is created in this folder the old file is deleted and replaced by the new file with the same name config8.



I write this code



       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");


I need to add a loop to check everytime if config9 is created.










share|improve this question


















  • 1





    Your opening paragraph implies if any new file is created in the folder. Your concluding remark is if only config9 is created. What is the exact requirement?

    – KevinO
    Nov 13 '18 at 12:55











  • Your code is very misleadingly laid-out, since you have a closing brace at the end of file2.renameTo(file1); }

    – khelwood
    Nov 13 '18 at 12:56











  • I just want to check if config9 is created in every time and thank you for your remark

    – olfa abdalah
    Nov 13 '18 at 12:58














-2












-2








-2








I have a folder that must contain always one file config8, and if a new file is created in this folder the old file is deleted and replaced by the new file with the same name config8.



I write this code



       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");


I need to add a loop to check everytime if config9 is created.










share|improve this question














I have a folder that must contain always one file config8, and if a new file is created in this folder the old file is deleted and replaced by the new file with the same name config8.



I write this code



       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");


I need to add a loop to check everytime if config9 is created.







java file loops






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 12:45









olfa abdalaholfa abdalah

11




11








  • 1





    Your opening paragraph implies if any new file is created in the folder. Your concluding remark is if only config9 is created. What is the exact requirement?

    – KevinO
    Nov 13 '18 at 12:55











  • Your code is very misleadingly laid-out, since you have a closing brace at the end of file2.renameTo(file1); }

    – khelwood
    Nov 13 '18 at 12:56











  • I just want to check if config9 is created in every time and thank you for your remark

    – olfa abdalah
    Nov 13 '18 at 12:58














  • 1





    Your opening paragraph implies if any new file is created in the folder. Your concluding remark is if only config9 is created. What is the exact requirement?

    – KevinO
    Nov 13 '18 at 12:55











  • Your code is very misleadingly laid-out, since you have a closing brace at the end of file2.renameTo(file1); }

    – khelwood
    Nov 13 '18 at 12:56











  • I just want to check if config9 is created in every time and thank you for your remark

    – olfa abdalah
    Nov 13 '18 at 12:58








1




1





Your opening paragraph implies if any new file is created in the folder. Your concluding remark is if only config9 is created. What is the exact requirement?

– KevinO
Nov 13 '18 at 12:55





Your opening paragraph implies if any new file is created in the folder. Your concluding remark is if only config9 is created. What is the exact requirement?

– KevinO
Nov 13 '18 at 12:55













Your code is very misleadingly laid-out, since you have a closing brace at the end of file2.renameTo(file1); }

– khelwood
Nov 13 '18 at 12:56





Your code is very misleadingly laid-out, since you have a closing brace at the end of file2.renameTo(file1); }

– khelwood
Nov 13 '18 at 12:56













I just want to check if config9 is created in every time and thank you for your remark

– olfa abdalah
Nov 13 '18 at 12:58





I just want to check if config9 is created in every time and thank you for your remark

– olfa abdalah
Nov 13 '18 at 12:58












2 Answers
2






active

oldest

votes


















2














Instead of a loop try a WatchService.



Basically you would be watching a particular directory for change and then you can react on this change.



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



For example :



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);
}


Then you can process your key events.






share|improve this answer


























  • You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

    – KevinO
    Nov 13 '18 at 13:13











  • I'm using jdk 1.6 and I don't know if WatchService is available or not

    – olfa abdalah
    Nov 13 '18 at 13:57



















0














If you have to solve this task with Java 1.6, you can use https://commons.apache.org/proper/commons-vfs/, version 2.1.



Here is an example for moving all incoming config files to "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);
}
}
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53281308%2floop-to-check-if-a-file-exists%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Instead of a loop try a WatchService.



    Basically you would be watching a particular directory for change and then you can react on this change.



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



    For example :



    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);
    }


    Then you can process your key events.






    share|improve this answer


























    • You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

      – KevinO
      Nov 13 '18 at 13:13











    • I'm using jdk 1.6 and I don't know if WatchService is available or not

      – olfa abdalah
      Nov 13 '18 at 13:57
















    2














    Instead of a loop try a WatchService.



    Basically you would be watching a particular directory for change and then you can react on this change.



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



    For example :



    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);
    }


    Then you can process your key events.






    share|improve this answer


























    • You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

      – KevinO
      Nov 13 '18 at 13:13











    • I'm using jdk 1.6 and I don't know if WatchService is available or not

      – olfa abdalah
      Nov 13 '18 at 13:57














    2












    2








    2







    Instead of a loop try a WatchService.



    Basically you would be watching a particular directory for change and then you can react on this change.



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



    For example :



    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);
    }


    Then you can process your key events.






    share|improve this answer















    Instead of a loop try a WatchService.



    Basically you would be watching a particular directory for change and then you can react on this change.



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



    For example :



    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);
    }


    Then you can process your key events.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 13 '18 at 13:17

























    answered Nov 13 '18 at 13:12









    Sayantan RoySayantan Roy

    8013




    8013













    • You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

      – KevinO
      Nov 13 '18 at 13:13











    • I'm using jdk 1.6 and I don't know if WatchService is available or not

      – olfa abdalah
      Nov 13 '18 at 13:57



















    • You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

      – KevinO
      Nov 13 '18 at 13:13











    • I'm using jdk 1.6 and I don't know if WatchService is available or not

      – olfa abdalah
      Nov 13 '18 at 13:57

















    You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

    – KevinO
    Nov 13 '18 at 13:13





    You might consider extracting the basics from the link to add to this answer. This one is close to a "link only" and might get tagged in a review.

    – KevinO
    Nov 13 '18 at 13:13













    I'm using jdk 1.6 and I don't know if WatchService is available or not

    – olfa abdalah
    Nov 13 '18 at 13:57





    I'm using jdk 1.6 and I don't know if WatchService is available or not

    – olfa abdalah
    Nov 13 '18 at 13:57













    0














    If you have to solve this task with Java 1.6, you can use https://commons.apache.org/proper/commons-vfs/, version 2.1.



    Here is an example for moving all incoming config files to "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);
    }
    }
    }





    share|improve this answer




























      0














      If you have to solve this task with Java 1.6, you can use https://commons.apache.org/proper/commons-vfs/, version 2.1.



      Here is an example for moving all incoming config files to "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);
      }
      }
      }





      share|improve this answer


























        0












        0








        0







        If you have to solve this task with Java 1.6, you can use https://commons.apache.org/proper/commons-vfs/, version 2.1.



        Here is an example for moving all incoming config files to "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);
        }
        }
        }





        share|improve this answer













        If you have to solve this task with Java 1.6, you can use https://commons.apache.org/proper/commons-vfs/, version 2.1.



        Here is an example for moving all incoming config files to "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);
        }
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 13:02









        WishmasterWishmaster

        11




        11






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53281308%2floop-to-check-if-a-file-exists%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly