Java中如何检测一个文件是否存在呢?
下文讲述Java代码中判断文件存在的方法分享,如下所示:
实现思路:
使用file实例的exists方法即可判断文件对象是否存在
使用file实例的isDirectory检测路径是否为文件夹
例:
package com.java265.other;
import java.io.File;
public class test {
/*
* java265.com 文件是否存在的示例分享
*/
public static void main(String[] args) throws Exception {
String s1 = "d:\\test.txt";
String s2 = "d:\\test8888.txt";
checkFileExists(s1);
System.out.println("===========");
checkFileExists(s2);
}
public static void checkFileExists(String filePath) {
File f = new File(filePath);
if (f.exists() && !f.isDirectory()) {
System.out.println(filePath + "此路径下-文件存在!");
} else {
System.out.println(filePath + "此路径下-文件不存在!");
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


