java判断给定路径或URL下的文件或文件夹是否存在?

if (file.exists()) { 来判断这是不是一个文件。
file.isDirectory() 来判断这是不是一个文件夹。

1.File testFile = new File(testFilePath);
if(!testFile .exists()) {
testFile.mkdirs();
System.out.println("测试文件夹不存在");
}
2.File testFile = new File(testFilePath);
if(!testFile .exists()) {
testFile.createNewFile();
System.out.println("测试文件不存在");
}
java中File类自带一个检测方法exists可以判断文件或文件夹是否存在,一般与mkdirs方法(该方法相较于mkdir可以创建包括父级路径,推荐使用该方法)或者createNewFile方法合作使用。
1,如果路径不存在,就创建该路径

java 判断url路径下文件是否存在

/**
      * 判断文件是否存在
      * @param httpPath
      * @return
      */
     private static Boolean existHttpPath(String httpPath){
         URL httpurl = null;
         try {
         httpurl = new URL(new URI(httpPath).toASCIIString());
         URLConnection urlConnection = httpurl.openConnection();
        // urlConnection.getInputStream();
        Long TotalSize=Long.parseLong(urlConnection.getHeaderField("Content-Length"));  
            if (TotalSize <= 0){
             return false;
            }
            return true;
         } catch (Exception e) {
             logger.debug(httpurl + "文件不存在");
         return false;
         }
         }

原文地址:https://www.cnblogs.com/bluestorm/p/9420909.html