简体   繁体   中英

In Java, how do I check if something is a directory, and if not, throw an exception?

I've created this new object:

File dir = new File(userHome + "//data")

In another class, I want verify that 'dir' is a directory and if it isn't, throw an IllegalArgumentException.

My goal is to then locate specific file types in that directory (if a directory) and process them.

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}else{
   throw new IllegalArgumentException();
}
new File(path).isDirectory(); 

This will return true if the File is a Directory.

File dir = new File(userHome + "//data");
if(dir.isDirectory()){
   //store files in an array of File
   fileArray = dir.listFiles();
}
else 
 //do whatever you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM