Example usage for java.io File canWrite

List of usage examples for java.io File canWrite

Introduction

In this page you can find the example usage for java.io File canWrite.

Prototype

public boolean canWrite() 

Source Link

Document

Tests whether the application can modify the file denoted by this abstract pathname.

Usage

From source file:fr.paris.lutece.maven.FileUtils.java

/**
 * Copy file from source to destination. The directories up to
 * <code>destination</code> will be created if they don't already exist.
 * <code>destination</code> will be overwritten if it already exists.
 *
 * @param source/*from   www .j ava2s .  com*/
 *            An existing non-directory <code>File</code> to copy bytes
 *            from.
 * @param destination
 *            A non-directory <code>File</code> to write bytes to
 *            (possibly overwriting).
 *
 * @throws IOException
 *             if <code>source</code> does not exist,
 *             <code>destination</code> cannot be written to, or an IO
 *             error occurs during copying.
 *
 * @throws java.io.FileNotFoundException
 *             if <code>destination</code> is a directory (use
 *             {@link #copyFileToDirectory}).
 */
public static void copyFile(final File source, final File destination) throws IOException {
    // check source exists
    if (!source.exists()) {
        final String message = "File " + source + " does not exist";
        throw new IOException(message);
    }

    // does destinations directory exist ?
    if ((destination.getParentFile() != null) && !destination.getParentFile().exists()) {
        destination.getParentFile().mkdirs();
    }

    // make sure we can write to destination
    if (destination.exists() && !destination.canWrite()) {
        final String message = "Unable to open file " + destination + " for writing.";
        throw new IOException(message);
    }

    FileInputStream input = null;
    FileOutputStream output = null;

    try {
        input = new FileInputStream(source);
        output = new FileOutputStream(destination);
        IOUtil.copy(input, output);
    } finally {
        IOUtil.close(input);
        IOUtil.close(output);
    }

    if (source.length() != destination.length()) {
        final String message = "Failed to copy full contents from " + source + " to " + destination;
        throw new IOException(message);
    }
}

From source file:com.piaoyou.util.FileUtil.java

public static void emptyFile(String srcFilename) throws IOException {
    File srcFile = new File(srcFilename);
    if (!srcFile.exists()) {
        throw new FileNotFoundException("Cannot find the file: " + srcFile.getAbsolutePath());
    }//ww  w  . j a  v  a  2 s.c  om
    if (!srcFile.canWrite()) {
        throw new IOException("Cannot write the file: " + srcFile.getAbsolutePath());
    }

    FileOutputStream outputStream = new FileOutputStream(srcFilename);
    outputStream.close();
}

From source file:com.appunity.ant.Utils.java

protected static File getNewWorkDir(Task task, String workdir, boolean... isClean)
        throws UnsupportedOperationException {
    String timedir = task.getProject().getProperty(" work.dir.timestamp");
    if (timedir != null && "true".equals(timedir)) {
        isUserTimeWorkDir = true;/*  ww  w . ja v a  2  s . c  o m*/
    }
    File dir = new File(Utils.obtainValidPath(task, workdir, "work.dir"));
    if (!dir.exists()) {
        System.out.println("make dir     :" + workdir);
        dir.mkdirs();
    } else {
        if (!dir.isDirectory()) {
            File oldfile = new File(workdir + ".bak");
            for (int i = 0; oldfile.exists(); i++) {
                oldfile = new File(workdir + "." + i + ".bak");
            }
            dir.renameTo(oldfile);
            System.out.println("make dir     :" + workdir);
            dir.mkdirs();
            System.out.println(
                    "work dir " + workdir + " is not a dir, will rename old file to " + oldfile.getName());
        }
    }
    if (!dir.canWrite()) {
        throw new UnsupportedOperationException("??: " + workdir);
    }
    if (isUserTimeWorkDir) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        File file = new File(dir, df.format(new Date()));
        while (file.exists()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
            file = new File(dir, df.format(new Date()));
        }
        file.mkdirs();
        return file;
    } else {
        if (isClean != null && isClean[0]) {
            for (File object : dir.listFiles()) {
                if (object.isDirectory()) {
                    try {
                        FileUtils.deleteDirectory(object);
                        System.out.println("delete old dir: " + object);
                    } catch (IOException ex) {
                        Logger.getLogger(InitProjectTask.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    object.delete();
                    System.out.println("delete old file: " + object);
                }
            }
        }
        currentWorkDir = dir;
        return dir;
    }
}

From source file:com.github.maven_nar.NarUtil.java

static Set findInstallNameToolCandidates(final File[] files, final Log log)
        throws MojoExecutionException, MojoFailureException {
    final HashSet candidates = new HashSet();

    for (final File file2 : files) {
        final File file = file2;

        if (!file.exists()) {
            continue;
        }//from   ww w  . j a  v  a2  s  . c om

        if (file.isDirectory()) {
            candidates.addAll(findInstallNameToolCandidates(file.listFiles(), log));
        }

        final String fileName = file.getName();
        if (file.isFile() && file.canWrite()
                && (fileName.endsWith(".so") || fileName.endsWith(".dylib") || fileName.endsWith(".jnilib"))) {
            candidates.add(file);
        }
    }

    return candidates;
}

From source file:dk.statsbiblioteket.util.Files.java

/**
 * Move a file with the same semantics as the standard Unix {@code move}
 * command./*from  w  ww .  ja v  a2 s.  c om*/
 *
 * In contrast to the standard Java {@link File#renameTo} this method
 * does extensive sanity checking and throws appropriate exceptions
 * if something is wrong.
 *
 * This method will cause quite a bit of {@code stat} dancing on the
 * file system, so don't use this method in performance critical regions.
 *
 * If {@code dest} is a directory {@code source} will be moved there keeping
 * its base name.
 * If {@code dest} does not exist {@code source} will be renamed to
 * {@code dest}.
 *
 * @param source    a writable file or directory
 * @param dest      either an existing writable directory, or non-existing file
 *                  with existing parent directory
 * @param overwrite if true and {@code dest} exists and is a regular
 *                  file it will be deleted before moving {@code source}
 *                  here
 * @throws FileNotFoundException      if either {@code source} or the parent
 *                                    directory of {@code dest} does not exist
 * @throws FileAlreadyExistsException if {@code dest} exists and is a
 *                                    regular file. If {@code overwrite}
 *                                    is {@code true} this exception will
 *                                    never be thrown
 * @throws FilePermissionException    if {@code source} or {@code dest} is not
 *                                    writable
 * @throws InvalidFileTypeException   if the parent of {@code dest} is a
 *                                    regular file
 * @throws IOException                if there is an unknown error during the move
 *                                    operation
 */
public static void move(File source, File dest, boolean overwrite) throws IOException {
    if (source == null) {
        throw new NullPointerException("Move source location is null");
    }
    if (dest == null) {
        throw new NullPointerException("Move destination is null");
    }

    /* source checks */
    if (!source.exists()) {
        throw new FileNotFoundException(source.toString());
    }
    if (!source.canWrite()) {
        throw new FilePermissionException(source, Files.Permission.writable);
    }

    /* dest checks */
    File destParent = dest.getParentFile();
    if (dest.exists() && dest.isFile() && !overwrite) {
        throw new FileAlreadyExistsException(dest);
    }
    if (!destParent.exists()) {
        throw new FileNotFoundException("Parent directory of " + dest + " " + "does not exist");
    }
    if (destParent.isFile()) {
        throw new InvalidFileTypeException(destParent, Files.Type.file);
    }
    if (dest.isFile() && !destParent.canWrite()) {
        throw new FilePermissionException(destParent, Files.Permission.writable);
    }

    /* If dest is a dir, move the file into it, keeping the base name */
    if (dest.isDirectory()) {
        if (!dest.canWrite()) {
            throw new FilePermissionException(dest, Files.Permission.writable);
        }
        dest = new File(dest, source.getName());
    }

    if (dest.exists()) {
        if (!overwrite) {
            throw new FileAlreadyExistsException(dest);
        }
        log.trace("Overwriting " + dest);
        Files.delete(dest);
    }

    log.trace("Set to move " + source + " to " + dest);

    // On some platform File.renameTo fails on the first runs. See
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298
    boolean result = false;
    for (int i = 0; i < 10; i++) {
        result = source.renameTo(dest);
        if (result) {
            break;
        }
        System.gc();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // Abort the move operation
            break;
        }
        log.trace("Retrying move (" + i + ")");
    }

    if (!result) {
        log.debug("Atomic move failed. Falling back to copy/delete");
        copy(source, dest, overwrite);
        delete(source);
    }

    log.debug("Moved " + source + " to " + dest);
}

From source file:com.piaoyou.util.FileUtil.java

/**
 * Write content to a fileName with the destEncoding
 *
 * @param content String/*ww  w  .  j  a v  a2 s.com*/
 * @param fileName String
 * @param destEncoding String
 * @throws FileNotFoundException
 * @throws IOException
 */
public static void writeFile(String content, String fileName, String destEncoding)
        throws FileNotFoundException, IOException {

    File file = null;
    try {
        file = new File(fileName);
        if (file.isFile() == false) {
            throw new IOException("'" + fileName + "' is not a file.");
        }
        if (file.canWrite() == false) {
            throw new IOException("'" + fileName + "' is a read-only file.");
        }
    } finally {
        // we don't have to close File here
    }

    BufferedWriter out = null;
    try {
        FileOutputStream fos = new FileOutputStream(fileName);
        out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding));

        out.write(content);
        out.flush();
    } catch (FileNotFoundException fe) {
        log.error("Error", fe);
        throw fe;
    } catch (IOException e) {
        log.error("Error", e);
        throw e;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException ex) {
        }
    }
}

From source file:com.twinsoft.convertigo.engine.util.FileUtils.java

public static void mergeDirectories(File srcDir, File destDir, boolean preserveFileDate) throws IOException {
    File[] files = srcDir.listFiles();
    if (files == null) { // null if security restricted
        throw new IOException("Failed to list contents of " + srcDir);
    }/*from   w  w  w  .  j  ava  2  s .c om*/
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (destDir.mkdirs() == false) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
        String message = "> Directory '" + destDir + "' created";
        if (Engine.logEngine != null) {
            Engine.logEngine.info(message);
        } else {
            System.out.println(message);
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    for (File file : files) {
        File copiedFile = new File(destDir, file.getName());
        if (file.isDirectory()) {
            mergeDirectories(file, copiedFile, preserveFileDate);
        } else {
            if (!copiedFile.exists()) {
                FileUtils.copyFile(file, copiedFile, preserveFileDate);
                String message = "+ File '" + file + "' copied from " + srcDir;
                if (Engine.logEngine != null) {
                    Engine.logEngine.info(message);
                } else {
                    System.out.println(message);
                }
            }
        }
    }
}

From source file:com.lee.sdk.utils.Utils.java

/**
 * ??//www . j a  v  a2s.c  o m
 * 
 * ??
 * 
 * @return true:?; false ?/mounted/??
 */
public static boolean isExternalStorageWriteable() {
    boolean writealbe = false;
    long start = System.currentTimeMillis();
    if (TextUtils.equals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState())) {
        File esd = Environment.getExternalStorageDirectory();
        if (esd.exists() && esd.canWrite()) {
            File file = new File(esd, ".696E5309-E4A7-27C0-A787-0B2CEBF1F1AB");
            if (file.exists()) {
                writealbe = true;
            } else {
                try {
                    writealbe = file.createNewFile();
                } catch (IOException e) {
                    if (DEBUG) {
                        Log.w(TAG, "isExternalStorageWriteable() can't create test file.");
                    }
                }
            }
        }
    }
    long end = System.currentTimeMillis();
    if (DEBUG) {
        Log.i(TAG, "Utility.isExternalStorageWriteable(" + writealbe + ") cost " + (end - start) + "ms.");
    }
    return writealbe;
}

From source file:com.piaoyou.util.FileUtil.java

public static void copyFile(String srcFilename, String destFilename, boolean overwrite) throws IOException {

    File srcFile = new File(srcFilename);
    if (!srcFile.exists()) {
        throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath());
    }// www .  j  a v  a  2  s. c o m
    if (!srcFile.canRead()) {
        throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath());
    }

    File destFile = new File(destFilename);
    if (overwrite == false) {
        if (destFile.exists()) {
            return;
        }
    } else {
        if (destFile.exists()) {
            if (!destFile.canWrite()) {
                throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
            }
        } else {
            if (!destFile.createNewFile()) {
                throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
            }
        }
    }

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {
        inputStream = new BufferedInputStream(new FileInputStream(srcFile));
        outputStream = new BufferedOutputStream(new FileOutputStream(destFile));
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
    }
}

From source file:com.github.maven_nar.NarUtil.java

public static void runRanlib(final File file, final Log log)
        throws MojoExecutionException, MojoFailureException {
    if (!file.exists()) {
        return;/*from   ww w.ja  v a  2  s. c o m*/
    }

    if (file.isDirectory()) {
        final File[] files = file.listFiles();
        for (final File file2 : files) {
            runRanlib(file2, log);
        }
    }
    if (file.isFile() && file.canWrite() && !file.isHidden() && file.getName().endsWith(".a")) {
        // ranlib file
        final int result = runCommand("ranlib", new String[] { file.getPath() }, null, null, log);
        if (result != 0) {
            throw new MojoExecutionException(
                    "Failed to execute 'ranlib " + file.getPath() + "'" + " return code: \'" + result + "\'.");
        }
    }
}