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; } }