Java Code Examples for java.io.File#exists()

The following examples show how to use java.io.File#exists() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CameraActivity.java    From AndroidProject with Apache License 2.0 7 votes vote down vote up
/**
 * 创建一个拍照图片文件对象
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File createCameraFile() {
    File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
    if (!folder.exists() || !folder.isDirectory()) {
        if (!folder.mkdirs()) {
            folder = Environment.getExternalStorageDirectory();
        }
    }

    try {
        File file = new File(folder, "IMG_" + new SimpleDateFormat("yyyyMMdd_kkmmss", Locale.getDefault()).format(new Date()) + ".jpg");
        file.createNewFile();
        return file;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 2
Source File: PluginClassLoaderTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link io.apiman.common.plugin.PluginClassLoader#loadClass(java.lang.String)}.
 * @throws Exception exception catch-all
 */
@Test
public void testLoadClass() throws Exception {
    File file = new File("src/test/resources/plugin.war");
    if (!file.exists()) {
        throw new Exception("Failed to find test WAR: plugin.war at: " + file.getAbsolutePath());
    }
    PluginClassLoader classloader = new TestPluginClassLoader(file);
    Class<?> class1 = classloader.loadClass("io.apiman.quickstarts.plugin.PluginMain");
    Method mainMethod = class1.getMethod("main", new String[0].getClass());
    mainMethod.invoke(null, new Object[1]);
    
    try {
        classloader.loadClass("io.apiman.notfound.MyClass");
        Assert.fail("Should have gotten a classnotfound here!");
    } catch (Exception e) {
        Assert.assertEquals("io.apiman.notfound.MyClass", e.getMessage());
    }
}
 
Example 3
Source File: ExpandWar.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Delete the specified directory, including all of its contents and
 * sub-directories recursively.
 *
 * @param dir File object representing the directory to be deleted
 * @param logFailure <code>true</code> if failure to delete the resource
 *                   should be logged
 * @return <code>true</code> if the deletion was successful
 */
public static boolean delete(File dir, boolean logFailure) {
    boolean result;
    if (dir.isDirectory()) {
        result = deleteDir(dir, logFailure);
    } else {
        if (dir.exists()) {
            result = dir.delete();
        } else {
            result = true;
        }
    }
    if (logFailure && !result) {
        log.error(sm.getString(
                "expandWar.deleteFailed", dir.getAbsolutePath()));
    }
    return result;
}
 
Example 4
Source File: AppStatus.java    From appstatus with Apache License 2.0 6 votes vote down vote up
public void setMaintenance(boolean maintenanceMode) throws IOException {
    this.maintenance = maintenanceMode;

    if (null == maintenanceFile) {
        return;
    }

    File modeFile = new File(maintenanceFile);

    if (maintenanceMode) {
        modeFile.createNewFile();
    } else if (modeFile.exists() && !modeFile.delete()) {
        throw new IOException("Unable to delete maintenance file");
    }

}
 
Example 5
Source File: ConfigurationFile.java    From GreasySpoon with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Load HttpServer configuration file and replace
 * <!--config--> tag in HTML by configuration content.
 * @param htmlcontent into which configuration file is inserted
 * @return updated HTML content
 */
public static String getConfigFile(String htmlcontent){
    String fileToEdit = HttpServer.configurationFile;
    File fich = new File(fileToEdit);
        if (!fich.exists()){
            return "";
        }// Endif
    StringBuilder sb = new StringBuilder();
    try {       
           BufferedReader in = new BufferedReader(new FileReader(fileToEdit));
           String str;
            //Read a line
            while ((str = in.readLine()) !=null ){
                sb.append(str).append("\r\n");
            }//End while readLine
            in.close();  
      } catch (IOException e){
          return "";
      }//End try&catch
      htmlcontent=htmlcontent.replace("<!--config-->", sb.toString());
      return htmlcontent;
}
 
Example 6
Source File: FileIoUtils.java    From restcommander with Apache License 2.0 6 votes vote down vote up
public static void createFolder(String folderPath) {

		File theDir = new File(folderPath);

		// if the directory does not exist, create it
		if (!theDir.exists()) {
			models.utils.LogUtils.printLogNormal("creating directory: " + folderPath);
			boolean result = theDir.mkdir();
			if (result) {
				models.utils.LogUtils.printLogNormal("directory just created now " + folderPath);
			}
		} else {
			models.utils.LogUtils.printLogNormal("directory " + folderPath + " already exist");
		}

	}
 
Example 7
Source File: MsgAdapter.java    From MaterialQQLite with Apache License 2.0 5 votes vote down vote up
private Bitmap getSessHeadPic(int nGroupCode, int nQQUin) {
   	GroupList groupList = m_QQClient.getGroupList();
   	BuddyInfo buddyInfo = groupList.getGroupMemberByCode(nGroupCode, nQQUin);
   	if (null == buddyInfo) {
   		return null;
   	}
   	
	if (0 == buddyInfo.m_nQQNum) {
		m_QQClient.updateGroupMemberNum(nGroupCode, nQQUin);
		return null;
	}

	Bitmap bmp = m_imgCache.get(buddyInfo.m_nQQNum);
	if (bmp != null) {
		return bmp;
	}

	String strFileName = m_QQClient.getSessHeadPicFullName(buddyInfo.m_nQQNum);
	File file = new File(strFileName);
	if (!file.exists()) {
		m_QQClient.updateGroupMemberHeadPic(nGroupCode, nQQUin, buddyInfo.m_nQQNum);
		return null;
	}
	
	LoadImageTask task = new LoadImageTask();
	task.m_strKey = String.valueOf(buddyInfo.m_nQQNum);
	task.m_strFileName = strFileName;
	task.execute("");
	return null;
}
 
Example 8
Source File: FileManagerServiceImpl.java    From efo with MIT License 5 votes vote down vote up
@Override
public void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException {
    File zip = ZipUtil.zip(new File(ValueConsts.USER_DESKTOP + File.separator + destFile), ValueConsts.FALSE,
            FileExecutor.getFiles(items));
    if (zip.exists()) {
        response.getOutputStream().write(FileExecutor.readFileToByteArray(zip));
        FileExecutor.deleteFile(zip);
    }
}
 
Example 9
Source File: IOUtils.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
public static boolean fileExists(File dir, String name) {
    File file = new File(dir, name);
    if (file.exists()) {
        if (file.isFile())
            return true;
        else
            throw new IllegalStateException("File exists but is not a file");
    }
    return false;
}
 
Example 10
Source File: CoverageMonitorTest.java    From teamengine with Apache License 2.0 5 votes vote down vote up
@After
public void deleteCoverageFile() {
    File file = new File(tempDir, COVERAGE_FILE);
    if (file.exists() && !file.delete()) {
        throw new RuntimeException("Failed to delete file at " + file);
    }
}
 
Example 11
Source File: PreviewUtil.java    From APDE with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Recursive file deletion
 *
 * @param file
 * @throws IOException
 */
public static void deleteFile(File file) throws IOException {
	if (file.exists()) {
		if (file.isDirectory()) {
			for (File content : file.listFiles()) {
				deleteFile(content);
			}
		}
		
		if (!file.delete()) { //Uh-oh...
			throw new FileNotFoundException("Failed to delete file: " + file);
		}
	}
}
 
Example 12
Source File: KaramelServiceApplication.java    From karamel with Apache License 2.0 5 votes vote down vote up
public static void create() {
  String name = "";
  try {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter cookbook name: ");
    name = br.readLine();
    File cb = new File("cookbooks" + File.separator + name);
    if (cb.exists()) {
      boolean wiped = false;
      while (!wiped) {
        System.out.print("Do you wan  t to over-write the existing cookbook " + name + "? (y/n) ");
        String overwrite = br.readLine();
        if (overwrite.compareToIgnoreCase("n") == 0 || overwrite.compareToIgnoreCase("no") == 0) {
          logger.info("Not over-writing. Exiting.");
          System.exit(0);
        }
        if (overwrite.compareToIgnoreCase("y") == 0 || overwrite.compareToIgnoreCase("yes") == 0) {
          deleteRecursive(cb);
          wiped = true;
        }
      }
    }
    String pathToCb = CookbookScaffolder.create(name);
    logger.info("New Cookbook is now located at: " + pathToCb);
    System.exit(0);
  } catch (IOException ex) {
    logger.error("", ex);
    System.exit(-1);
  }
}
 
Example 13
Source File: FileUtils.java    From ssj with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Copies an asset to a target location
 *
 * @param context
 * @param srcPath
 * @param targetPath
 */
public static void copyAsset(Context context, String srcPath, String targetPath)
{
	try
	{
		InputStream in = context.getAssets().open(srcPath);

		File targetFile = new File(targetPath);

		if(!targetFile.exists())
		{
			new File(targetFile.getParent()).mkdirs();
		}

		OutputStream out = new FileOutputStream(targetFile);

		// Copy files
		copyFile(in, out);

		// Close streams
		in.close();
		out.flush();
		out.close();
	}
	catch (IOException e)
	{
		Log.e("Failed to copy asset " + srcPath, e);
	}
}
 
Example 14
Source File: StorageUtils.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
/**
 * Returns individual application cache directory (for only image caching from ImageLoader). Cache directory will be
 * created on SD card <i>("/Android/data/[app_package_name]/cache/uil-images")</i> if card is mounted and app has
 * appropriate permission. Else - Android defines cache directory on device's file system.
 *
 * @param context Application context
 * @return Cache {@link File directory}
 */
public static File getIndividualCacheDirectory(Context context) {
	File cacheDir = getCacheDirectory(context);
	File individualCacheDir = new File(cacheDir, INDIVIDUAL_DIR_NAME);
	if (!individualCacheDir.exists()) {
		if (!individualCacheDir.mkdir()) {
			individualCacheDir = cacheDir;
		}
	}
	return individualCacheDir;
}
 
Example 15
Source File: DevOps.java    From dew with Apache License 2.0 5 votes vote down vote up
/**
 * UnSkip this project.
 *
 * @param project the maven project
 */
public static void unSkip(MavenProject project) {
    File skipFile = new File(project.getBasedir().getPath() + File.separator + "target" + File.separator + ".dew_skip_flag");
    if (skipFile.exists()) {
        skipFile.delete();
    }
}
 
Example 16
Source File: BOSWebServerManager.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected void addBonitaWar(final File targetFolder, final IProgressMonitor monitor) throws IOException {
    final File webappDir = new File(targetFolder, "webapps");
    final File targetBonitaWarFile = new File(webappDir, "bonita.war");
    if (!targetBonitaWarFile.exists()) {
        BonitaStudioLog.debug("Copying Bonita war in tomcat/server/webapps...", EnginePlugin.PLUGIN_ID);
        final URL url = ProjectUtil.getConsoleLibsBundle().getResource("tomcat/server/webapp");
        final File bonitaWarFile = new File(FileLocator.toFileURL(url).getFile(), "bonita.war");
        PlatformUtil.copyResource(webappDir, bonitaWarFile, monitor);
        BonitaStudioLog.debug("Bonita war copied in tomcat/server/webapps.",
                EnginePlugin.PLUGIN_ID);
    }
}
 
Example 17
Source File: ProfileComparer.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private String cachedFetch(String id, String source) throws IOException {
  String tmpDir = System.getProperty("java.io.tmpdir");
  String local = Utilities.path(tmpDir, id);
  File f = new File(local);
  if (f.exists())
    return TextFile.fileToString(f);
  URL url = new URL(source);
  URLConnection c = url.openConnection();
  String result = TextFile.streamToString(c.getInputStream());
  TextFile.stringToFile(result, f);
  return result;
}
 
Example 18
Source File: UserDatabase.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PostConstruct
public synchronized void loadDatabase(){
    File backupFile = new File(BACKUPFILENAME);
    if (backupFile.exists() && backupFile.isFile()) {
        try (ObjectInputStream backup = new ObjectInputStream(new FileInputStream(BACKUPFILENAME))){
            users = (Set<String>) backup.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            WebauthnTutorialLogger.logp(Level.WARNING, CLASSNAME, "loadDatabase",
                    "WEBAUTHN-MSG-1001", ex.getLocalizedMessage());
        }
    }
}
 
Example 19
Source File: NewTermDbBaseInfoPage.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 输入验证器 ;
 */
private IStatus validator() {
	// 选择数据库类型的时候初始化dbMetaDate
	if (null == dbMetaData) {
		return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg1"));
	}
	//

	String dbName = dbModel.getDbName();
	String instance = dbModel.getInstance();
	String host = dbModel.getHost();
	String port = dbModel.getPort();
	String location = dbModel.getItlDBLocation();
	String username = dbModel.getUserName();
	String password = dbModel.getPassword();

	if (dbName == null || dbName.trim().length() == 0) {
		return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg2"));
	}

	String vRs = DbValidator.valiateDbName(dbName);
	if (vRs != null) {
		return ValidationStatus.error(vRs);
	}

	if (dbMetaData.instanceSupported()) {
		if (instance == null || instance.trim().length() == 0) {
			return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.instancemsg"));
		}
		dbMetaData.setInstance(instance == null ? "" : instance);
	}

	if (dbMetaData.dataPathSupported()) {
		if (location == null || location.trim().length() == 0) {
			return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg3"));
		}
		File f = new File(location);
		if (!f.isDirectory() || !f.exists()) {
			return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg11"));
		}
	}

	if (dbMetaData.serverNameSupported()) {
		if (host == null || host.trim().length() == 0) {
			return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg4"));
		}
	}
	if (dbMetaData.portSupported()) {
		if (port == null || !port.matches("[0-9]+")) {
			return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg5"));
		}
	}
	if (dbMetaData.userNameSupported()) {
		if (username == null || username.trim().length() == 0) {
			return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg6"));
		}
	}

	dbMetaData.setDatabaseName(dbName == null ? "" : dbName);
	dbMetaData.setDataPath(location == null ? "" : location);
	dbMetaData.setServerName(host == null ? "" : host);
	dbMetaData.setPort(port == null ? "" : port);
	dbMetaData.setUserName(username == null ? "" : username);
	dbMetaData.setPassword(password == null ? "" : password); // 密码可以为空

	return ValidationStatus.ok();
}
 
Example 20
Source File: PrometheusConfig.java    From monsoon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void setConfigFile(File file) throws IOException {
    if (!file.isAbsolute()) throw new IOException("file name must be absolute: " + file.toString());
    if (!file.exists()) throw new IOException("file not found: " + file.toString());
    if (!file.isFile()) throw new IOException("expected a proper file: " + file.toString());
    config_file_ = file.getCanonicalFile();
}