Java程序检查文件是否存在
在本文中,我们将学习如何使用Java检查文件是否存在。程序演示了如何使用java.io.File类的exists()方法来执行此检查。
Java.io.File.exists()方法
java.io.File.exists()方法如果文件路径存在,则返回true,否则返回false。参数:此方法不接受任何参数。返回值:它返回一个布尔值,指示由抽象路径指定的文件是否存在。
在Java中检查文件是否存在
以下是检查文件是否存在的方法:−
- 步骤1. 使用Try-Catch块:在文件创建或检查期间可能发生的任何异常,都使用try-catch块来处理。
- 步骤2. 创建文件对象:使用文件名“demo1.txt”创建一个File对象。
File file = new File("demo1.txt");
- 步骤3. 创建新文件:调用createNewFile()方法,如果文件不存在则创建它。
file.createNewFile();
- 步骤4. 检查文件是否存在:使用exists()方法检查文件是否存在。
Java程序检查文件是否存在
演示此功能的程序如下:−
import java.io.File;
public class Demo {
public static void main(String[] args) {
try {
File file = new File("demo1.txt");
file.createNewFile();
System.out.println("File exists? " + file.exists());
} catch(Exception e) {
e.printStackTrace();
}
}
}
输出
File exists? true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP