检查文件是否已存在于同一路径中

时间:2017-02-22 22:23:17

标签: java file printwriter

我想检查同一文件夹中是否已存在特定文件。 如果它不存在则创建一个新文件并键入某些内容。 例如。如果filePath = test.txt和test.txt不存在。 创建一个新的文件名test.txt并将12345放在该文件的第一行。

目前我的方法甚至不会运行这个if语句,尽管满足条件。 (test.txt不存在)

    PrintWriter output;
    File file = new File(filePath);
    if(!file.isFile()){
        try {
            output = new PrintWriter(new FileWriter(filePath));
        } catch (IOException ex) {
            throw new PersistenceException("Error!", ex);
        }
        output.print("12345");
        output.flush();
        output.close();
    }

1 个答案:

答案 0 :(得分:2)

您可以通过创建File对象并使用exists方法来检查文件是否存在。与C相比,java中的文件对象不同,当您创建File对象时,不一定要创建物理文件。

File file = new File(pathString);
if (file.exists())
{
    //  File already exists
}
else
{
    //  You can create your new file
}