How do I check if a file exists in Java?

后端 未结 17 2764
盖世英雄少女心
盖世英雄少女心 2020-11-22 00:50

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s -e $filename

17条回答
  •  不要未来只要你来
    2020-11-22 01:16

    Simple example with good coding practices and covering all cases :

     private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
            File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
            if (f.exists()) {
                throw new FileAlreadyExistsException(f.getAbsolutePath());
            } else {
                try {
                    URL u = new URL(url);
                    FileUtils.copyURLToFile(u, f);
                } catch (MalformedURLException ex) {
                    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    

    Reference and more examples at

    https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations

提交回复
热议问题