Android File Create verifyCanCreateFile(final String path, final long length)

Here you can find the source of verifyCanCreateFile(final String path, final long length)

Description

Checks if a file with a specified size can be created on a specified path.

License

Open Source License

Parameter

Parameter Description
path the file path
length the size of the file in bytes

Return

true if the file can be created, false if the file already exists or if the file creation fails, for example, because the file specified is a directory.

Declaration

public static boolean verifyCanCreateFile(final String path,
        final long length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.RandomAccessFile;

public class Main {
    /**/*ww w . j  a  va  2s.  c  o m*/
     * Checks if a file with a specified size can be created on a specified path.
     * <p>
     * This method effectively tries to create a file with the specified size. Then it
     * tries to enlarge the file. In the end the file is removed.
     * 
     * @param path the file path
     * @param length the size of the file in bytes
     * @return <code>true</code> if the file can be created, <code>false</code> if the
     *         file already exists or if the file creation fails, for example, because the
     *         file specified is a directory.
     */
    public static boolean verifyCanCreateFile(final String path,
            final long length) {
        final File file = new File(path);
        if (!file.exists()) {
            final RandomAccessFile access;
            try {
                access = new RandomAccessFile(file, "rws");
            } catch (FileNotFoundException e) {
                return false;
            }
            try {
                access.setLength(length);
                access.close();
            } catch (IOException e) {
                return false;
            }

            return file.delete();
        }
        return false;
    }
}

Related

  1. getFile(String filepath)
  2. getOutputMediaFile(Context context)
  3. makeFile(File file)
  4. makeFile(String destinctionFile)
  5. overwriteFile(File file)
  6. createTemporaryFile(String part, String ext)