Home> Java> JavaBase> body text

java determines whether a file exists in a folder

angryTom
Release: 2019-11-14 15:50:51
Original
5786 people have browsed it

java determines whether a file exists in a folder

java Determine whether a file exists in a folder

1. First use the File class to create a File object;

2. Then determine whether it is a directory. If it is not a directory, return

3. Then use the file.list() method to obtain the files in the directory and store them in the array

4. Finally determine If the array length is greater than 0, the file exists.

The code is as follows:

/** * 读取某个文件夹下的所有文件 */ public static boolean hasfile(String filepath) throws FileNotFoundException, IOException { try { File file = new File(filepath); if (!file.isDirectory()) { System.out.println("请输入一个目录"); return false; } else if (file.isDirectory()) { String[] filelist = file.list(); if (filelist.length) { System.out.println("该目录下存在文件"); } } } catch (FileNotFoundException e) { System.out.println("readfile() Exception:" + e.getMessage()); } return true; }
Copy after login

Use:

System.out.println( hasfile("c:/users/admin/desktop") ? "存在文件" : "不存在文件" );
Copy after login

php Chinese website, a large number of freeJava introductory tutorials, welcome to learn online!

The above is the detailed content of java determines whether a file exists in a folder. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!