CodeGym /Java 博客 /随机的 /Java 判断文件是否存在的方法
John Squirrels
第 41 级
San Francisco

Java 判断文件是否存在的方法

已在 随机的 群组中发布

为什么我们需要检查文件是否“存在”?

在处理文件操作(读/写/创建/删除/更新等)时,许多新手可能想知道为什么我们甚至需要检查文件是否存在?对此的适当回应是,为了避免NoSuchFileException,访问文件始终是一种更安全的方式。因此,您需要在访问文件之前检查文件是否存在,以避免任何运行时异常。Java 中如何判断一个文件是否存在 - 1

如何使用 file.exists() 方法进行检查?

Java 提供了一个简单的布尔方法file.exists(),它不需要任何参数来检查给定路径上的相关文件。检查文件是否存在时,请考虑 3 种情况。
  • 文件已找到。
  • 找不到该文件。
  • 如果未授予权限(出于安全原因),文件状态未知。
如果找到文件,File.exists()方法返回“ true ”。如果找不到或访问失败,则返回“ false ”。

例子

让我们看一个简单的代码示例来了解实现。

package com.java.exists;
import java.io.File;

public class ExistsMethodInJava {

	public static void main(String[] args) {

		String filePath = "C:\\Users\\Lubaina\\Documents\\myNewTestFile.txt";
		File file = new File(filePath);

		// check if the file exists at the file path
		System.out.println("Does File exists at \"" + filePath + "\"?\t" + file.exists());
		
		filePath = "C:\\Users\\Lubaina\\Documents\\myOtherTestFile.txt";
		File nextFile = new File(filePath);
		
		// check if the file exists at the file path
		System.out.println("Does File exists at \"" + filePath + "\"?\t" + nextFile.exists());
	}
}
输出
文件是否存在于“C:\Users\Lubaina\Documents\myNewTestFile.txt”?true 文件是否存在于“C:\Users\Lubaina\Documents\myOtherTestFile.txt”?错误的
请注意file.exists()方法也适用于“目录”路径。如果您使用此方法检查有效的目录路径,它将返回 true 否则返回 false。为了更好地理解,您可以查看以下代码块。

package com.java.exists;
import java.io.File;

public class CheckFileExists {

	// check if the "file" resource exists and not "directory"
	public static boolean checkFileExists(File file) {
		return file.exists() && !file.isDirectory();
	}

	public static void main(String[] args) {

		String directoryPath = "C:\\Users\\Lubaina\\Documents\\javaContent";
		File direcotry = new File(directoryPath);

		// check if the directory exists at the dir path
		if (direcotry.exists()) {
			System.out.println("Direcotry at \"" + directoryPath + "\" exists.\n");
		} else {
			System.out.println("Direcotry at \"" + directoryPath + "\" does not exist.\n");
		}

		// check if the resource present at the path is a "file" not "directory"
		boolean check = checkFileExists(direcotry);
		System.out.println("Is the resource \"" + direcotry + "\" a File? " + check);

		String filePath = "C:\\Users\\Lubaina\\Documents\\myNewTestFile.txt";
		File file = new File(filePath);
		check = checkFileExists(file);
		System.out.println("Is the resource \"" + file + "\" a File? " + check);
	}
}
输出
“C:\Users\Lubaina\Documents\javaContent”目录存在。资源“C:\Users\Lubaina\Documents\javaContent”是一个文件吗?false 资源“C:\Users\Lubaina\Documents\myNewTestFile.txt”是一个文件吗?真的
从输出中可以看出,名为“javaContent”的目录已通过exists()方法验证。所以如果你特别想检查一个文件是不是目录,可以使用Java中 File类提供的boolean方法isDirectory() 。

结论

到本文结束时,您必须熟悉如何在 Java 中检查文件是否存在。您可以编写自己的程序来测试和理解此功能。一旦您熟悉了它,您也可以探索检查文件是否存在的其他方法(例如,使用符号链接或 nio 类)。祝你好运,编码愉快!:)
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION