Как проверить, существует ли файл в Java?

Помимо упоминаний других ответов, стоит также упомянуть, что в C ++ 0x {} инициализация не сужается. Поэтому вместо получения предупреждения вы получите ошибку, например,

void f(int x)
{
   // code
}

int main()
{
   f({3.14}); // narrowing conversion of '3.14000000000000012434497875801753252744674682617e+0' from 'double' to 'int' inside { }
}

g ++ 4.4 и выше список инициализаторов поддержки (с опцией -std=c++0x)

778
задан Community 23 May 2017 в 12:18
поделиться

6 ответов

Using java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}
1301
ответ дан 22 November 2019 в 21:19
поделиться

Также стоит ознакомиться с Commons FileUtils https: // commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html У него есть дополнительные методы управления файлами, и он часто лучше, чем JDK.

4
ответ дан 22 November 2019 в 21:19
поделиться

первое обращение по запросу «java файл существует» в Google:

import java.io.*;

public class FileTest {
    public static void main(String args[]) {
        File f = new File(args[0]);
        System.out.println(f + (f.exists()? " is found " : " is missing "));
    }
}
14
ответ дан 22 November 2019 в 21:19
поделиться

Вы можете использовать следующее: File.exists ()

14
ответ дан 22 November 2019 в 21:19
поделиться
f.isFile() && f.canRead()
25
ответ дан 22 November 2019 в 21:19
поделиться

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

413
ответ дан 22 November 2019 в 21:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: