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:cz.etnetera.reesmo.writer.storage.FileSystemStorage.java

protected File convertModelIdToDir(String modelId) throws StorageException {
    if (modelId == null) {
        throw new StorageException("Model directory is uknown because of empty model id");
    }//from   ww  w  . j ava  2 s . com
    File file = getModelIdDir(modelId);
    if (!file.exists())
        throw new StorageException("Model directory does not exists: " + file);
    if (!file.isDirectory())
        throw new StorageException("Model directory is not directory: " + file);
    if (!file.canWrite())
        throw new StorageException("Model directory is not writable: " + file);
    return file;
}

From source file:cz.cas.lib.proarc.common.config.AppConfiguration.java

private void copyConfigTemplateImpl(File configHome) throws IOException {
    File cfgFile = new File(configHome, CONFIG_FILE_NAME + ".template");
    if (!cfgFile.exists() || cfgFile.exists() && cfgFile.isFile() && cfgFile.canWrite()) {
        Enumeration<URL> resources = AppConfiguration.class.getClassLoader()
                .getResources(DEFAULT_PROPERTIES_RESOURCE);
        URL lastResource = null;//  w w w  .ja  v a2 s.co m
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            lastResource = url;
            System.out.println(url.toExternalForm());
        }

        if (lastResource == null) {
            throw new IllegalStateException(DEFAULT_PROPERTIES_RESOURCE);
        }
        InputStream resource = lastResource.openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(resource, "ISO-8859-1"));
        try {
            // we need platform dependent line separator => PrintWriter
            PrintWriter writer = new PrintWriter(cfgFile, "UTF-8");
            try {
                for (String line; (line = reader.readLine()) != null;) {
                    writer.println(line);
                }
                writer.println();
            } finally {
                writer.close();
            }
        } finally {
            reader.close();
        }

    }
}

From source file:net.orpiske.sdm.lib.io.support.ShieldAwareCopier.java

@Override
protected void handleFile(File file, int depth, Collection results) throws IOException {
    File destinationFile = new File(destination, file.getName());

    if (!ShieldUtils.isShielded(destinationFile)) {
        FileUtils.copyFile(file, destinationFile);

        destinationFile.setExecutable(file.canExecute());
        destinationFile.setReadable(file.canRead());
        destinationFile.setWritable(file.canWrite());
    } else {/*from   ww w  .ja v a 2  s .  c  o  m*/
        System.out.println("Ignoring shielded file " + file.getPath());
    }
}

From source file:com.buaa.cfs.utils.FileUtil.java

/**
 * Platform independent implementation for {@link File#canWrite()}
 *
 * @param f input file//  ww w  .j  ava  2s.  co m
 *
 * @return On Unix, same as {@link File#canWrite()} On Windows, true if process has write access on the path
 */
public static boolean canWrite(File f) {
    if (Shell.WINDOWS) {
        try {
            return NativeIO.Windows.access(f.getCanonicalPath(), NativeIO.Windows.AccessRight.ACCESS_WRITE);
        } catch (IOException e) {
            return false;
        }
    } else {
        return f.canWrite();
    }
}

From source file:maspack.fileutil.SafeFileUtils.java

/**
 * Copies a file to a new location./*from w  w w .  ja v a  2  s  . c  om*/
 * <p>
 * This method copies the contents of the specified source file to the
 * specified destination file. The directory holding the destination file is
 * created if it does not exist. If the destination file exists, then this
 * method will overwrite it.
 * <p>
 * <strong>Note:</strong> Setting <code>preserveFileDate</code> to
 * {@code true} tries to preserve the file's last modified date/times using
 * {@link File#setLastModified(long)}, however it is not guaranteed that the
 * operation will succeed. If the modification operation fails, no indication
 * is provided.
 *
 * @param srcFile
 * an existing file to copy, must not be {@code null}
 * @param destFile
 * the new file, must not be {@code null}
 * @param options
 * determine whether to use file locks and preserve date information
 *
 * @throws NullPointerException
 * if source or destination is {@code null}
 * @throws IOException
 * if source or destination is invalid
 * @throws IOException
 * if an IO error occurs during copying
 */
public static void copyFile(File srcFile, File destFile, int options) throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (srcFile.exists() == false) {
        throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
    }
    if (srcFile.isDirectory()) {
        throw new IOException("Source '" + srcFile + "' exists but is a directory");
    }
    if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
        throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
    }
    File parentFile = destFile.getParentFile();
    if (parentFile != null) {
        if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
            throw new IOException("Destination '" + parentFile + "' directory cannot be created");
        }
    }
    if (destFile.exists() && destFile.canWrite() == false) {
        throw new IOException("Destination '" + destFile + "' exists but is read-only");
    }
    doCopyFile(srcFile, destFile, options);
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.cache.FilePersistingCache.java

public CachedFile put(final @Nullable String namespace, final GridFSDBFile gfsFile) throws IOException {
    checkArgument(gfsFile != null && isNotBlank(gfsFile.getFilename()) && isNotBlank(gfsFile.getMD5()),
            "Uninitialized or invalid file");
    File outfile = null;
    try {// w ww .j  ava 2  s . co  m
        final String uuid = randomUUID().toString();
        outfile = new File(new File(cacheDir, uuid.substring(0, 2)), uuid);
        final File parentDir = outfile.getParentFile();
        if (parentDir.exists() || parentDir.mkdirs())
            ;
        if ((outfile.isFile() && outfile.canWrite()) || outfile.createNewFile())
            ;
        final CachedFile cachedFile = CachedFile.builder().cachedFilename(outfile.getCanonicalPath())
                .md5(gfsFile.getMD5()).build();
        gfsFile.writeTo(outfile);
        CACHE.put(toKey(namespace, gfsFile.getFilename()), cachedFile);
        return cachedFile;
    } catch (Exception e) {
        deleteQuietly(outfile);
        throw e;
    }
}

From source file:com.isencia.passerelle.runtime.repos.impl.filesystem.FlowRepositoryServiceImpl.java

@Override
public FlowHandle commit(String flowCode, Flow flow) throws DuplicateEntryException {
    File newFlowFolder = new File(rootFolder, flowCode);
    if (newFlowFolder.exists()) {
        throw new DuplicateEntryException(flowCode);
    } else {/*from  w w  w .  j  ava 2  s . c  o  m*/
        FlowHandle flowHandle = null;
        VersionSpecification vSpec = new ThreeDigitVersionSpecification(1, 0, 0);
        File versionFolder = new File(newFlowFolder, vSpec.toString());
        versionFolder.mkdirs();
        File destinationFile = new File(versionFolder, flow.getName() + ".moml");
        if ((!destinationFile.exists() || destinationFile.canWrite())) {
            BufferedWriter outputWriter = null;
            try {
                outputWriter = new BufferedWriter(new FileWriter(destinationFile));
                flow.exportMoML(outputWriter);
                flowHandle = new FlowHandleImpl(flowCode, destinationFile, vSpec);
                writeMetaData(flowCode, VERSION_ACTIVE, vSpec.toString());
                writeMetaData(flowCode, VERSION_MOSTRECENT, vSpec.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (EntryNotFoundException e) {
                // should not happen
            } finally {
                if (outputWriter != null) {
                    try {
                        outputWriter.flush();
                        outputWriter.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
            return flowHandle;
        } else {
            throw new RuntimeException(new IOException("File not writable " + destinationFile));
        }
    }
}

From source file:com.tecapro.inventory.common.util.FileLocalUtil.java

/**
 * check file Deletable//from ww w  .jav  a 2 s.co  m
 */
public boolean isDeletable(String name, int index) {
    File file = new File(baseDir, name);
    return file.isFile() && file.canWrite();
}

From source file:de.rub.syssec.saaf.gui.frame.CfgSelectorFrame.java

/**
 * Copies the generated PNG to the specified directory. The directory must be
 * specified in the config.//from  w  ww.j ava  2 s.com
 * 
 * @param cfg the CFG to copy
 */
private void safeCopy(File cfg) {
    String cfgValue = Config.getInstance().getConfigValue(ConfigKeys.DIRECTORY_CFGS);
    File externalDir = null;
    boolean error = false;
    if (cfgValue != null) {
        externalDir = new File(cfgValue);
        if (!externalDir.exists() || !externalDir.isDirectory() || !externalDir.canWrite()) {
            error = true;
        }
    } else {
        error = true;
    }
    if (error) {
        MainWindow.showErrorDialog("Could not save CFG(s). Option " + ConfigKeys.DIRECTORY_CFGS.toString()
                + " not properly set in saaf.conf.", "Error");
        return;
    }

    String name = smaliClass.getApplication().getApplicationDirectory().getName();
    String bytecodeDir = smaliClass.getApplication().getBytecodeDirectory().getName();

    int posByteCodeName = cfg.getAbsolutePath().lastIndexOf(bytecodeDir);
    String path = cfg.getAbsolutePath().substring(posByteCodeName + bytecodeDir.length() + 1);
    File targetFile = new File(
            externalDir + File.separator + name + File.separator + path.replace(File.separator, "."));

    try {
        if (!targetFile.exists() || (cfg.length() != targetFile.length())) {
            FileUtils.copyFile(cfg, targetFile);
        }
    } catch (IOException e) {
        e.printStackTrace();
        MainWindow.showErrorDialog("Could not save CFG(s): " + e.getMessage(), "Error");
    }

}

From source file:com.storageroomapp.client.sample.StorageRoomClient.java

private boolean getAndDeleteCollection(Collection col, String[] args) {
    boolean success = true;

    if (args.length < 5) {
        log.error("Directory name on command line does not exist.");
        return false;
    }//from   w  w  w. j a v a  2 s .  c  om
    String folderToWriteDataPath = args[4];

    File folderToWriteData = new File(folderToWriteDataPath);
    if (!folderToWriteData.exists()) {
        log.error("Directory [" + folderToWriteDataPath + "] does not exist.");
        return false;
    }
    if (!folderToWriteData.canWrite()) {
        log.error("Directory [" + folderToWriteDataPath + "] is not writable.");
        return false;
    }

    String pk = col.getPk();
    CollectionEntries entries = col.getEntries();
    PageOfEntries results = entries.queryAll();

    boolean done = false;
    while (!done) {
        for (Entry entry : results.asIterable()) {

            String entryPK = null;
            if (pk != null) {
                GenericField<?> entryPKField = entry.get(pk);
                entryPK = entryPKField.getValueWrapper().toString();
            }
            if (entryPK == null) {
                entryPK = entry.getInternalUniqueIdentifier();
            }

            // write out the json data
            String entryAsString = entry.toJSONString(true);
            File entryFile = new File(folderToWriteData, entryPK + ".json");
            FileUtil.writeStringToFile(entryFile, entryAsString);

            // write out any File/Image fields as separate files
            for (GenericField<?> field : entry.asListOfDataFieldsOnly()) {
                if (field.isCompoundFieldType()) {
                    if (field instanceof FileField) {
                        FileField fileField = (FileField) field;
                        StorageRoomClient.writeFileFieldToFile(entryPK, fileField, folderToWriteData);
                    } else if (field instanceof ImageField) {
                        ImageField imageField = (ImageField) field;
                        StorageRoomClient.writeImageFieldToFiles(entryPK, imageField, folderToWriteData);
                    }
                }
            }

            BooleanField protectFromAutoDelete = (BooleanField) entry.get("do_not_auto_delete");
            if ((protectFromAutoDelete == null) || !protectFromAutoDelete.getValueWrapper().getInnerValue()) {
                log.info("Deleting Item [" + entry.getName() + "]");
                entry.delete();
            }
        }
        if (results.getNumResultsPages() == 1) {
            // done = true; // the natural way
            try {
                Thread.sleep(15 * 60 * 1000);
            } catch (InterruptedException ie) {
            }
        } else {
            results = results.jumpPage(0);
            if (results == null) {
                // nothing left
                try {
                    Thread.sleep(15 * 60 * 1000);
                } catch (InterruptedException ie) {
                }
            }
        }
    }
    return success;
}