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

The following are Jave code examples for showing how to use exists() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: n4js   File: AbstractExportToSingleFileWizardPage.java   View Source Code Vote up 6 votes
/**
 * Returns a boolean indicating whether the passed File handle is is valid and available for use.
 */
protected boolean ensureTargetFileIsValid(File targetFile) {
	if (targetFile.exists() && targetFile.isDirectory()) {
		displayErrorDialog(N4ExportMessages.Export_mustBeFile);
		giveFocusToDestination();
		return false;
	}

	if (targetFile.exists()) {
		if (targetFile.canWrite()) {
			if (!this.overwriteExistingFilesCheckbox.getSelection()
					&& !queryYesNoQuestion(N4ExportMessages.Export_alreadyExists)) {
				return false;
			}
		} else {
			displayErrorDialog(N4ExportMessages.Export_alreadyExistsError);
			giveFocusToDestination();
			return false;
		}
	}
	return true;
}
 
Example 2
Project: incubator-netbeans   File: ArchetypeWizardUtils.java   View Source Code Vote up 6 votes
public static void createFromArchetype(File projDir, ProjectInfo vi, Archetype arch, @NullAllowed Map<String,String> additional, boolean updateLastUsedProjectDir) throws IOException {
    final File parent = projDir.getParentFile();
    if (parent == null) {
        throw new IOException("no parent of " + projDir);
    }
    if (updateLastUsedProjectDir && parent != null && parent.exists()) {
        ProjectChooser.setProjectsFolder(parent);
    }
    if (!parent.isDirectory() && !parent.mkdirs()) {
        throw new IOException("could not create " + parent);
    }
    runArchetype(parent, vi, arch, additional);
}
 
Example 3
Project: incubator-netbeans   File: DerbyDatabasesImpl.java   View Source Code Vote up 6 votes
/**
 * Checks if the given database exists in the Derby system home.
 *
 * @return true if the database exists, false otherwise.
 *
 * @throws NullPointerException if <code>databaseName</code> is null.
 */
public  boolean databaseExists(String databaseName) {
    if (databaseName == null) {
        throw new NullPointerException("The databaseName parameter cannot be null"); // NOI18N
    }
    // just because it makes sense, not really needed anywhere probably
    if ("".equals(databaseName)) { // NOI18N
        return false;
    }

    String systemHome = DerbySupport.getSystemHome();
    if (systemHome.length() <= 0) { // NOI18N
        return false;
    }
    File databaseFile = new File(systemHome, databaseName);
    return databaseFile.exists();
}
 
Example 4
Project: javaide   File: DexClassLoader.java   View Source Code Vote up 6 votes
/**
 * Finds a native library. This method is called after the parent
 * ClassLoader has failed to find a native library of the same name.
 *
 * @param libname The name of the library to find
 * @return the complete path of the library, or {@code null} if the library
 * is not found.
 */
@Override
protected String findLibrary(String libname) {
    ensureInit();

    String fileName = System.mapLibraryName(libname);
    for (int i = 0; i < mLibPaths.length; i++) {
        String pathName = mLibPaths[i] + fileName;
        File test = new File(pathName);

        if (test.exists()) {
            if (VERBOSE_DEBUG)
                System.out.println("  found " + libname);
            return pathName;
        }
    }

    if (VERBOSE_DEBUG)
        System.out.println("  library " + libname + " not found");
    return null;
}
 
Example 5
Project: incubator-netbeans   File: BuildZipDistributionTest.java   View Source Code Vote up 6 votes
private File createNewJarFile (String prefix) throws IOException {
    if (prefix == null) {
        prefix = "modules";
    }
    
    File dir = new File(this.getWorkDir(), prefix);
    dir.mkdirs();
    
    int i = 0;
    for (;;) {
        File f = new File (dir, i++ + ".jar");
        if (!f.exists ()) {
            f.createNewFile();
            return f;
        }
    }
}
 
Example 6
Project: Spring-web-shop-project   File: PicturesServiceTest.java   View Source Code Vote up 6 votes
@Test
public void saveOneWithUrlExistNameInDirectory() {
    Picture picture = pictures.getFirst();
    Picture secondPicture = new Picture(picture.getPath(), picture.getName(), picture.getFileType());

    service.save(picture, URL);
    service.save(secondPicture, URL);

    assertTrue(picture.equals(service.findOne(picture)));
    assertNull("Error\n(Check your directory, and delete picture with name \"name0\" if exist from last test?)", service.findOne(secondPicture));
    File f = new File(picture.getPath() + picture.getName() + picture.getFileType());
    if (f.exists() && !f.isDirectory())
        service.delete(picture);
    else
        fail("the picture wasn't created");
}
 
Example 7
Project: SlotNSlot_Android   File: DownloaderService.java   View Source Code Vote up 6 votes
/**
 * Creates a filename (where the file should be saved) from info about a
 * download.
 */
public String generateSaveFile(String filename, long filesize)
        throws GenerateSaveFileError {
    String path = generateTempSaveFileName(filename);
    File expPath = new File(path);
    if (!Helpers.isExternalMediaMounted()) {
        Log.d(Constants.TAG, "External media not mounted: " + path);
        throw new GenerateSaveFileError(STATUS_DEVICE_NOT_FOUND_ERROR,
                "external media is not yet mounted");

    }
    if (expPath.exists()) {
        Log.d(Constants.TAG, "File already exists: " + path);
        throw new GenerateSaveFileError(STATUS_FILE_ALREADY_EXISTS_ERROR,
                "requested destination file already exists");
    }
    if (Helpers.getAvailableBytes(Helpers.getFilesystemRoot(path)) < filesize) {
        throw new GenerateSaveFileError(STATUS_INSUFFICIENT_SPACE_ERROR,
                "insufficient space on external storage");
    }
    return path;
}
 
Example 8
Project: LuaViewPlayground   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * delete a file
 *
 * @param file
 */
public static void delete(File file) {
    if (file != null && file.exists()) {
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    delete(child);
                }
            }
            file.delete();
        } else {
            file.delete();
        }
    }
}
 
Example 9
Project: lams   File: DiskMultipartRequestHandler.java   View Source Code Vote up 5 votes
protected void createDiskFile(MultipartElement element) {
    File tempFile = element.getFile();
    if (tempFile.exists()) {
        DiskFile theFile = new DiskFile(tempFile.getAbsolutePath());
        theFile.setContentType(element.getContentType());
        theFile.setFileName(element.getFileName());
        theFile.setFileSize((int) tempFile.length());
        fileElements.put(element.getName(), theFile);
        allElements.put(element.getName(), theFile);
    }
}
 
Example 10
Project: updateUtils   File: UpdateManager.java   View Source Code Vote up 5 votes
public static Builder create(Context context) {
    File file = new File(context.getExternalFilesDir("").getParentFile(), "cache");
    if (file != null && !file.exists()) {
        file.mkdirs();
    }
    UpdateUtil.log("===>>> " + context.getExternalCacheDir());
    return new Builder(context).setWifiOnly(sIsWifiOnly);
}
 
Example 11
Project: BaseCore   File: ZipUtils.java   View Source Code Vote up 5 votes
/**
 * 解压缩一个文件
 *
 * @param zipFile    压缩文件
 * @param folderPath 解压缩的目标目录
 * @throws IOException 当解压缩过程出错时抛出
 */
public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
    File desDir = new File(folderPath);
    if (!desDir.exists()) {
        desDir.mkdirs();
    }
    ZipFile zf = new ZipFile(zipFile);
    for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
        ZipEntry entry = ((ZipEntry) entries.nextElement());
        InputStream in = zf.getInputStream(entry);
        String str = folderPath + File.separator + entry.getName();
        str = new String(str.getBytes("8859_1"), "GB2312");
        File desFile = new File(str);
        if (!desFile.exists()) {
            File fileParentDir = desFile.getParentFile();
            if (!fileParentDir.exists()) {
                fileParentDir.mkdirs();
            }
            desFile.createNewFile();
        }
        OutputStream out = new FileOutputStream(desFile);
        byte buffer[] = new byte[BUFF_SIZE];
        int realLength;
        while ((realLength = in.read(buffer)) > 0) {
            out.write(buffer, 0, realLength);
        }
        in.close();
        out.close();
    }
}
 
Example 12
Project: Banmanager   File: Metrics.java   View Source Code Vote up 5 votes
/**
 * Writes a String to a file. It also adds a note for the user,
 *
 * @param file The file to write to. Cannot be null.
 * @param lines The lines to write.
 * @throws IOException If something did not work :(
 */
private void writeFile(File file, String... lines) throws IOException {
    if (!file.exists()) {
        file.createNewFile();
    }
    try (
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
    ) {
        for (String line : lines) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
    }
}
 
Example 13
Project: dremio-oss   File: LocalSyncableFileSystem.java   View Source Code Vote up 5 votes
public LocalSyncableOutputStream(Path path) throws FileNotFoundException {
  File dir = new File(path.getParent().toString());
  if (!dir.exists()) {
    boolean success = dir.mkdirs();
    if (!success) {
      throw new FileNotFoundException("failed to create parent directory");
    }
  }
  fos = new FileOutputStream(path.toString());
  output = new BufferedOutputStream(fos, 64*1024);
}
 
Example 14
Project: knime-json-node-doc-generator   File: JsonNodeDocuGenerator.java   View Source Code Vote up 5 votes
@Override
public Object start(final IApplicationContext context) throws Exception {
	Object o = context.getArguments().get(IApplicationContext.APPLICATION_ARGS);
	Display.getDefault();
	if (o != null && o instanceof String[]) {
		String[] args = (String[]) o;
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(DESTINATION_ARG)) {
				m_directory = new File(args[i + 1]);
			} else if (args[i].equals(CATEGORY_ARG)) {
				m_catPath = args[i + 1];
			} else if (args[i].equals(PLUGIN_ARG)) {
				m_pluginIds.add(args[i + 1]);
			} else if (args[i].equals(INCLUDE_DEPRECATED_ARG)) {
				m_includeDeprecated = true;
			} else if (args[i].equals("-help")) {
				printUsage();
				return EXIT_OK;
			}
		}
	}

	if (m_directory == null) {
		System.err.println("No output directory specified");
		printUsage();
		return 1;
	} else if (!m_directory.exists() && !m_directory.mkdirs()) {
		System.err.println("Could not create output directory '" + m_directory.getAbsolutePath() + "'.");
		return 1;
	}

	generate();

	return EXIT_OK;
}
 
Example 15
Project: chromium-net-for-android   File: TestFilesInstaller.java   View Source Code Vote up 5 votes
/**
 * Copies a file from assets to the device's file system.
 * @param context
 * @param srcFilePath the source file path in assets.
 * @param destFilePath the destination file path.
 * @throws IllegalStateException if the destination file already exists.
 */
@SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE")
private static void copyTestFile(Context context, String srcFilePath, String destFilePath)
        throws IOException {
    File destFile = new File(destFilePath);
    if (destFile.exists()) {
        throw new IllegalStateException(srcFilePath + " already exists.");
    }

    if (!FileUtils.extractAsset(context, srcFilePath, destFile)) {
        throw new IOException("Could not extract asset " + srcFilePath + ".");
    }
}
 
Example 16
Project: SuperHttp   File: DiskLruCache.java   View Source Code Vote up 5 votes
private static void deleteIfExists(File file) throws IOException {
  if (file.exists() && !file.delete()) {
    throw new IOException();
  }
}
 
Example 17
Project: TestChat   File: CrashHandler.java   View Source Code Vote up 5 votes
/**
 * 导出异常信息到SD卡
 *
 * @param ex
 */
private File dumpExceptionToSDCard(Throwable ex) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return null;
        }
        //创建文件夹
        File dir = new File(PATH);
        if (!dir.exists()) {
                dir.mkdirs();
        }
        //获取当前时间
        long current = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
        //以当前时间创建log文件
        File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
        try {
                //输出流操作
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
                //导出手机信息和异常信息
                PackageManager pm = mContext.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
                pw.println("发生异常时间:" + time);
                pw.println("应用版本:" + pi.versionName);
                pw.println("应用版本号:" + pi.versionCode);
                pw.println("android版本号:" + Build.VERSION.RELEASE);
                pw.println("android版本号API:" + Build.VERSION.SDK_INT);
                pw.println("手机制造商:" + Build.MANUFACTURER);
                pw.println("手机型号:" + Build.MODEL);
                ex.printStackTrace(pw);
                //关闭输出流
                pw.close();
        } catch (Exception e) {
        }
        if (UserManager.getInstance().getCurrentUser() != null) {
                ChatDB.create().saveOrUpdateCrashMessage(file.getAbsolutePath(), true);
        }
        return file;
}
 
Example 18
Project: GitHub   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * 判断文件是否存在,存在则在创建之前删除
 *
 * @param file 文件
 * @return {@code true}: 创建成功<br>{@code false}: 创建失败
 */
public static boolean createFileByDeleteOldFile(final File file) {
    if (file == null) return false;
    // 文件存在并且删除失败返回false
    if (file.exists() && !file.delete()) return false;
    // 创建目录失败返回false
    if (!createOrExistsDir(file.getParentFile())) return false;
    try {
        return file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 19
Project: oscm   File: CreateKPITask.java   View Source Code Vote up 4 votes
private void validateFile(String file) throws FileNotFoundException {
    File fileToValidation = new File(file);
    if (!fileToValidation.exists()) {
        throw new FileNotFoundException("File " + fileToValidation.getAbsolutePath() + " not found");
    }
}
 
Example 20
Project: FreshMember   File: DaemonStrategy23.java   View Source Code Vote up 4 votes
private void createNewFile(File dirFile, String fileName) throws IOException{
	File file = new File(dirFile, fileName);
	if(!file.exists()){
		file.createNewFile();
	}
}