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:it.geosolutions.tools.compress.file.Extractor.java

/**
 * Unzips the files from a zipfile into a directory. All of the files will be put in a single
 * direcotry. If the zipfile contains a hierarchycal structure, it will be ignored.
 * //  w  w  w  . ja v a 2  s.  c  o  m
 * @param zipFile
 *            The zipfile to be examined
 * @param destDir
 *            The direcotry where the extracted files will be stored.
 * @return The list of the extracted files, or null if an error occurred.
 * @throws IllegalArgumentException
 *             if the destination dir is not writeable.
 * @deprecated use Extractor.unZip instead which support complex zip structure
 */
public static List<File> unzipFlat(final File zipFile, final File destDir) {
    // if (!destDir.isDirectory())
    // throw new IllegalArgumentException("Not a directory '" + destDir.getAbsolutePath()
    // + "'");

    if (!destDir.canWrite())
        throw new IllegalArgumentException("Unwritable directory '" + destDir.getAbsolutePath() + "'");

    try {
        List<File> ret = new ArrayList<File>();
        ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile));

        for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream
                .getNextEntry()) {
            String entryName = zipentry.getName();
            if (zipentry.isDirectory())
                continue;

            File outFile = new File(destDir, entryName);
            ret.add(outFile);
            FileOutputStream fileoutputstream = new FileOutputStream(outFile);

            org.apache.commons.io.IOUtils.copy(zipinputstream, fileoutputstream);
            fileoutputstream.close();
            zipinputstream.closeEntry();
        }

        zipinputstream.close();
        return ret;
    } catch (Exception e) {
        LOGGER.warn("Error unzipping file '" + zipFile.getAbsolutePath() + "'", e);
        return null;
    }
}

From source file:FileCopy.java

public static void copy(String fromFileName, String toFileName) throws IOException {
    File fromFile = new File(fromFileName);
    File toFile = new File(toFileName);

    if (!fromFile.exists())
        throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
    if (!fromFile.isFile())
        throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
    if (!fromFile.canRead())
        throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);

    if (toFile.isDirectory())
        toFile = new File(toFile, fromFile.getName());

    if (toFile.exists()) {
        if (!toFile.canWrite())
            throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
        System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): ");
        System.out.flush();/*from   www.j ava2s.c  o  m*/
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String response = in.readLine();
        if (!response.equals("Y") && !response.equals("y"))
            throw new IOException("FileCopy: " + "existing file was not overwritten.");
    } else {
        String parent = toFile.getParent();
        if (parent == null)
            parent = System.getProperty("user.dir");
        File dir = new File(parent);
        if (!dir.exists())
            throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
        if (dir.isFile())
            throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
        if (!dir.canWrite())
            throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
    }

    FileInputStream from = null;
    FileOutputStream to = null;
    try {
        from = new FileInputStream(fromFile);
        to = new FileOutputStream(toFile);
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = from.read(buffer)) != -1)
            to.write(buffer, 0, bytesRead); // write
    } finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:edu.ku.brc.specify.tools.FixMetaTags.java

/**
* Change the contents of text file in its entirety, overwriting any
* existing text./*from w ww . j a va 2s.c  om*/
*
* This style of implementation throws all exceptions to the caller.
*
* @param aFile is an existing file which can be written to.
* @throws IllegalArgumentException if param does not comply.
* @throws FileNotFoundException if the file does not exist.
* @throws IOException if problem encountered during write.
*/
static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
    if (aFile == null) {
        throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
        throw new FileNotFoundException("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
        throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
        throw new IllegalArgumentException("File cannot be written: " + aFile);
    }

    //declared here only to make visible to finally clause; generic reference
    Writer output = null;
    try {
        //use buffering
        //FileWriter always assumes default encoding is OK!
        output = new BufferedWriter(new FileWriter(aFile));
        output.write(aContents);
    } finally {
        //flush and close both "output" and its underlying FileWriter
        if (output != null)
            output.close();
    }
}

From source file:hk.idv.kenson.jrconsole.Console.java

/**
 * Checking the param is ready to generate the report or not
 * @param params Parameters to be checked
 * @throws IllegalArgumentException The exception talking about the which argument is invalid
 *//*from  ww  w.j  a  va 2 s  . c  om*/
private static void checkParam(Map<String, Object> params) throws IllegalArgumentException {
    log.debug("Checking runtime parameters...");
    //Checking the data-source
    if (params.get("source") == null)
        throw new IllegalArgumentException("Please specify the data-source");
    if (params.get("type") == null)
        params.put("type", "jdbc");
    String type = params.get("type").toString();
    if (!(type.equals("jdbc") || type.equals("json") || type.equals("xml") || type.equals("csv")))
        throw new IllegalArgumentException("type \"" + type + "\" is not supported");
    if (!("jdbc".equals(type) || !"pipe".equals(params.get("source")))) {
        File file = new File(params.get("source").toString());
        if (!(file.exists() && file.isFile()))
            throw new IllegalArgumentException("The source file is not exists: " + params.get("source"));
        if (!file.canRead())
            throw new IllegalArgumentException("The source file is not readable: " + params.get("source"));
    }

    //Checking the report template
    if (params.get("jrxml") == null && params.get("jasper") == null)
        throw new IllegalArgumentException("Please specify -jrxml or -jasper for loading report template");
    if (params.get("jrxml") != null) {
        File jrxml = new File(params.get("jrxml").toString());
        if (!jrxml.exists())
            throw new IllegalArgumentException("jrxml \"" + params.get("jrxml") + "\" is not exists");
        if (!jrxml.canRead())
            throw new IllegalArgumentException("jrxml \"" + params.get("jrxml") + "\" is not readable");
    }
    if (params.get("jasper") != null) {
        File jasper = new File(params.get("jasper").toString());
        if (!jasper.exists())
            throw new IllegalArgumentException("jasper \"" + params.get("jasper") + "\" is not exists");
        if (!jasper.canRead())
            throw new IllegalArgumentException("jasper \"" + params.get("jasper") + "\" is not readable");
    }

    //Checking output
    if (params.get("outputtype") == null)
        params.put("outputtype", "pdf");
    if (params.get("output") == null)
        params.put("output", System.getProperty("user.dir") + "/output.pdf");
    File output = new File(params.get("output").toString());
    if (output.exists() && !output.canWrite())
        throw new IllegalArgumentException("output \"" + params.get("output") + "\" cannot be overwrited");

    //Checking the locale and bundle
    try {
        if (params.get("locale") != null)
            params.put(PARAM_LOCALE, getLocale(params.remove("locale").toString()));
        if (params.get(PARAM_LOCALE) == null)
            params.put(PARAM_LOCALE, Locale.getDefault());
        if (params.get("bundle") != null)
            params.put(PARAM_BUNDLE, parseVal("bundle:" + params.get("bundle"), params));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error when reading properties/locale/resource-bundle", ex);
    }
}

From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java

public static void checkIsWritable(File element) throws IOException {
    if (element.canWrite() == false) {
        throw new IOException("\"" + element.getPath() + "\" is not writable");
    }/*  w w  w.ja v a 2  s. c om*/
}

From source file:com.themodernway.server.core.io.IO.java

public static final boolean isWritable(final File file) {
    return file.canWrite();
}

From source file:net.community.chest.gitcloud.facade.ConfigUtils.java

/**
 * Checks that a give property value that represents a folder is valid as follows:</BR>
 * <UL>/*  w w w  . j a  v a2s .  c o  m*/
 *      <LI>If exists, then it must be a folder with read/write/execute permissions</LI>
 *      <LI>Otherwise, it is created along with its parents</LI>
 * <UL>
 * @param propName The property name (used for meaningful exception message)
 * @param propValue The {@link File} to verify
 * @return <code>false</code> if this is an already existing folder, <code>true</code>
 * if had to create it (and its parents)
 * @throws IllegalStateException if any of the validation tests fails
 * @see File#mkdirs()
 */
public static final boolean verifyFolderProperty(String propName, File propValue) throws IllegalStateException {
    if (propValue.exists()) {
        if (!propValue.isDirectory()) {
            throw new IllegalStateException("verifyFolderProperty(" + propName + ") not a folder: "
                    + ExtendedFileUtils.toString(propValue));
        }

        if (!propValue.canRead()) {
            throw new IllegalStateException("verifyFolderProperty(" + propName + ") non-readable: "
                    + ExtendedFileUtils.toString(propValue));
        }

        if (!propValue.canWrite()) {
            throw new IllegalStateException("verifyFolderProperty(" + propName + ") non-writeable: "
                    + ExtendedFileUtils.toString(propValue));
        }

        if (!propValue.canExecute()) {
            throw new IllegalStateException("verifyFolderProperty(" + propName + ") non-listable: "
                    + ExtendedFileUtils.toString(propValue));
        }

        return false;
    } else {
        if (!propValue.mkdirs()) {
            throw new IllegalStateException("verifyFolderProperty(" + propName + ") failed to create: "
                    + ExtendedFileUtils.toString(propValue));
        }

        return true;
    }
}

From source file:gov.nasa.arc.spife.europa.clientside.EuropaServerManager.java

private static boolean isFileWritable(String file) {
    org.eclipse.emf.common.util.URI uri = org.eclipse.emf.common.util.URI.createURI(file);
    if (URIConverter.INSTANCE.exists(uri, null)) {
        Map<String, Set<String>> options = new TreeMap<String, Set<String>>();
        Set<String> attributes = new TreeSet<String>();
        attributes.add(URIConverter.ATTRIBUTE_READ_ONLY);
        options.put(URIConverter.OPTION_REQUESTED_ATTRIBUTES, attributes);

        Map<String, ?> readOnly = URIConverter.INSTANCE.getAttributes(uri, options);
        return !((Boolean) readOnly.get(URIConverter.ATTRIBUTE_READ_ONLY));
    } else {/*from   www  .  java 2s.co m*/
        File foo = new File(file);
        return foo.canWrite();
    }
}

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

public static void copyFileAttributes(@Nonnull final File from, @Nonnull final File to) {
    to.setExecutable(from.canExecute());
    to.setReadable(from.canRead());//from   ww  w.  j  a  va  2s. co  m
    to.setWritable(from.canWrite());
}

From source file:com.csipsimple.utils.PreferencesWrapper.java

private static File getStorageFolder() {
    File root = Environment.getExternalStorageDirectory();

    if (root.canWrite()) {
        File dir = new File(root.getAbsolutePath() + File.separator + "CSipSimple");
        if (!dir.exists()) {
            dir.mkdirs();//from   w w w  .j ava2  s. c  om
            Log.d(THIS_FILE, "Create directory " + dir.getAbsolutePath());
        }
        return dir;
    }
    return null;
}