I am playing a bit with the new Java 7 IO features, actually I trying to receive all the xml files of a folder. But this throws an exception when the folder does not exist,
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
Generate a file from the string of your folder directory
String path="Folder directory";
File file = new File(path);
and use method exist.
If you want to generate the folder you sould use mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
You need to transform your Path into a File
and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
There is no need to separately call the exists()
method, as isDirectory()
implicitly checks whether the directory exists or not.
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;