How do I check if a file exists in Java?

后端 未结 17 2420
盖世英雄少女心
盖世英雄少女心 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:19

    Don't use File constructor with String.
    This may not work!
    Instead of this use URI:

    File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
    if(f.exists() && !f.isDirectory()) { 
        // to do
    }
    

提交回复
热议问题