如何检查Java中是否存在文件

java.io.File class exists() method can be used to check if file exists or not in java. If file exists, it returns true else this method returns false.

java.io.Fileexist()方法可用于检查java中文件是否存在。 如果文件存在,则返回true,否则此方法返回false。

Java检查文件是否存在 (Java Check if File Exists)

Let’s look at a simple program to check if a file exists or not in Java.

让我们看一个简单的程序,检查Java中文件是否存在。

package com.journaldev.files;

import java.io.File;
import java.io.IOException;

public class FileExists {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/source.txt");
        File notExist = new File("xyz.txt");
        
        try {
            System.out.println(file.getCanonicalPath() + " exists? "+file.exists());
            System.out.println(notExist.getCanonicalPath() + " exists? "+notExist.exists());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

}

Output of the above program is:

上面程序的输出是:

/Users/pankaj/source.txt exists? true
/Users/pankaj/JavaPrograms/xyz.txt exists? false

Note: When we provide a relative path to create a file object, Eclipse uses project root as the base directory. If you are running the program from the command line, then the current directory is used as the base directory.

注意 :当我们提供创建文件对象的相对路径时,Eclipse使用项目根目录作为基本目录。 如果从命令行运行程序,则将当前目录用作基本目录。

Read following post to know about java file path, canonical path and absolute path.

阅读以下文章,以了解Java文件路径,规范路径和绝对路径

GitHub Repository. GitHub存储库中签出更多Java IO示例。

翻译自: https://www.journaldev.com/912/java-check-if-file-exists

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值