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; }
Use:
System.out.println( hasfile("c:/users/admin/desktop") ? "存在文件" : "不存在文件" );
php Chinese website, a large number of free Java 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!