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:com.github.maven_nar.NarUtil.java

public static void makeExecutable(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) {
            makeExecutable(file2, log);
        }
    }
    if (file.isFile() && file.canRead() && file.canWrite() && !file.isHidden()) {
        // chmod +x file
        final int result = runCommand("chmod", new String[] { "+x", file.getPath() }, null, null, log);
        if (result != 0) {
            throw new MojoExecutionException("Failed to execute 'chmod +x " + file.getPath() + "'"
                    + " return code: \'" + result + "\'.");
        }
    }
}

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

public static void makeLink(final File file, final Log log)
        throws MojoExecutionException, MojoFailureException {
    if (!file.exists()) {
        return;/*from  ww w.  jav  a  2  s. co  m*/
    }

    if (file.isDirectory()) {
        final File[] files = file.listFiles();
        for (final File file2 : files) {
            makeLink(file2, log);
        }
    }
    if (file.isFile() && file.canRead() && file.canWrite() && !file.isHidden()
            && file.getName().matches(".*\\.so(\\.\\d+)+$")) {
        final File sofile = new File(file.getParent(),
                file.getName().substring(0, file.getName().indexOf(".so") + 3));
        if (!sofile.exists()) {
            // ln -s lib.so.xx lib.so
            final int result = runCommand("ln", new String[] { "-s", file.getName(), sofile.getPath() }, null,
                    null, log);
            if (result != 0) {
                throw new MojoExecutionException("Failed to execute 'ln -s " + file.getName() + " "
                        + sofile.getPath() + "'" + " return code: \'" + result + "\'.");
            }
        }
    }
}

From source file:de.qucosa.webapi.v1.FileHandlingService.java

private void assertIsWriteable(File f) throws Exception {
    if (!f.canWrite()) {
        throw new Exception("Given path is not writeable: " + documentsPath);
    }// w w  w  .  j  a va  2 s . c om
}

From source file:com.iksgmbh.sql.pojomemodb.utils.FileUtil.java

/**
 * Uses streams to perform copy//  www . ja v  a  2 s.co m
 * @param fromFile
 * @param toFile
 * @throws IOException
 */
public static void copyBinaryFile(final File fromFile, File toFile) {
    if (!fromFile.exists())
        throw new RuntimeException("FileCopy: " + "no such source file: " + fromFile.getAbsolutePath());
    if (!fromFile.isFile())
        throw new RuntimeException("FileCopy: " + "can't copy directory: " + fromFile.getAbsolutePath());
    if (!fromFile.canRead())
        throw new RuntimeException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsolutePath());

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

    if (toFile.exists()) {
        if (!toFile.canWrite())
            throw new RuntimeException(
                    "FileCopy: " + "destination file is unwriteable: " + toFile.getAbsolutePath());
    } else {
        String parent = toFile.getParent();
        if (parent == null)
            parent = System.getProperty("user.dir");
        File dir = new File(parent);
        if (!dir.exists())
            throw new RuntimeException("FileCopy: " + "destination directory doesn't exist: " + parent);
        if (dir.isFile())
            throw new RuntimeException("FileCopy: " + "destination is not a directory: " + parent);
        if (!dir.canWrite())
            throw new RuntimeException("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
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:com.github.riccardove.easyjasub.EasyJaSubInputFromCommand.java

private static void checkOutputFile(String fileName, File file) throws EasyJaSubException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new EasyJaSubException("Invalid output file, " + fileName + " is a directory");
        }/* w w  w .  jav  a2  s .c o  m*/
        return;
    }
    File directory = file.getAbsoluteFile();
    do {
        directory = directory.getParentFile();
    } while (directory != null && !directory.exists());
    if (directory != null && !directory.canWrite()) {
        throw new EasyJaSubException(
                "Can not write on " + directory.getAbsolutePath() + " to create " + fileName);
    }
}

From source file:com.meltmedia.cadmium.core.config.impl.PropertiesWriterImpl.java

@Override
public void persistProperties(Properties properties, File propsFile, String message, Logger log) {

    if (propsFile.canWrite() || !propsFile.exists()) {

        FileOutputStream out = null;

        try {//  w ww  . ja  va2s  .  c om

            ensureDirExists(propsFile.getParent());
            out = new FileOutputStream(propsFile);
            properties.store(out, message);
            out.flush();
        } catch (Exception e) {

            log.warn("Failed to persist vault properties file.", e);
        } finally {
            IOUtils.closeQuietly(out);
        }

    }

}

From source file:edu.buffalo.cse.pigout.Main.java

public static String validateLogFile(String logFileName, String scriptName) {
    String strippedDownScriptName = null;

    // script name
    if (scriptName != null) {
        File scriptFile = new File(scriptName);
        if (!scriptFile.isDirectory()) {
            String scriptFileAbsPath;
            try {
                scriptFileAbsPath = scriptFile.getCanonicalPath();
                strippedDownScriptName = getFileFromCanonicalPath(scriptFileAbsPath);
            } catch (IOException ioe) {
                log.warn("Could not compute canonical path to the script file " + ioe.getMessage());
                strippedDownScriptName = null;
            }//from  ww  w  .j  av  a2  s. c  o  m
        }
    }

    String defaultLogFileName = (strippedDownScriptName == null ? "pigout_" : strippedDownScriptName)
            + new Date().getTime() + ".log";
    File logFile;

    if (logFileName != null) {
        logFile = new File(logFileName);

        //Check if the file name is a directory
        //append the default file name to the file
        if (logFile.isDirectory()) {
            if (logFile.canWrite()) {
                try {
                    logFileName = logFile.getCanonicalPath() + File.separator + defaultLogFileName;
                } catch (IOException ioe) {
                    log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                    return null;
                }
                return logFileName;
            } else {
                log.warn("Need write permission in the directory: " + logFileName + " to create log file.");
                return null;
            }
        } else {
            //we have a relative path or an absolute path to the log file
            //check if we can write to the directory where this file is/will be stored
            if (logFile.exists()) {
                if (logFile.canWrite()) {
                    try {
                        logFileName = new File(logFileName).getCanonicalPath();
                    } catch (IOException ioe) {
                        log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                        return null;
                    }
                    return logFileName;
                } else {
                    //do not have write permissions for the log file
                    //bail out with an error message
                    log.warn("Cannot write to file: " + logFileName + ". Need write permission.");
                    return logFileName;
                }
            } else {
                logFile = logFile.getParentFile();

                if (logFile != null) {
                    //if the directory is writable we are good to go
                    if (logFile.canWrite()) {
                        try {
                            logFileName = new File(logFileName).getCanonicalPath();
                        } catch (IOException ioe) {
                            log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                            return null;
                        }
                        return logFileName;
                    } else {
                        log.warn("Need write permission in the directory: " + logFile + " to create log file.");
                        return logFileName;
                    }
                } //end if logFile != null else is the default in fall through
            } //end else part of logFile.exists()
        } //end else part of logFile.isDirectory()
    } //end if logFileName != null

    //file name is null or its in the current working directory
    //revert to the current working directory
    String currDir = System.getProperty("user.dir");
    logFile = new File(currDir);
    logFileName = currDir + File.separator + (logFileName == null ? defaultLogFileName : logFileName);
    if (logFile.canWrite()) {
        return logFileName;
    }
    log.warn("Cannot write to log file: " + logFileName);
    return null;
}

From source file:info.magnolia.ui.form.field.upload.DefaultFileFactory.java

public DefaultFileFactory(File directory, SimpleTranslator i18n) {
    if (directory.isDirectory() && directory.canWrite()) {
        this.directory = directory;
    } else {/*from w ww  .j  a  va  2  s.  co m*/
        throw new IllegalArgumentException(i18n.translate("ui-form.filefactory.nonexitantdirectory"));
    }
}

From source file:com.feilong.commons.core.io.FileUtil.java

/**
 * ?file./*from   ww w.j  a v a2s .co  m*/
 *
 * @param filePath
 *            file
 * @return the file
 * @throws IllegalArgumentException
 *             if Validator.isNullOrEmpty(filePath)
 * @see #getFormatFileName(String)
 * @since 1.0.7
 */
static final File cascadeMkdirs(final String filePath) throws IllegalArgumentException {
    if (Validator.isNullOrEmpty(filePath)) {
        throw new IllegalArgumentException("filePath can't be null/empty!");
    }

    File file = new File(filePath);

    if (file.exists()) {
        // 
        if (file.isDirectory()) {
            log.error("File '" + file + "' exists but is a directory");
            throw new IllegalArgumentException("File '" + file + "' exists but is a directory");
        }
        // ?
        else if (!file.canWrite()) {
            log.error("File '" + file + "' cannot be written to");
            throw new IllegalArgumentException("File '" + file + "' cannot be written to");
        }
    }
    // ?
    else {
        File parent = file.getParentFile();
        if (parent != null && !parent.exists()) {
            boolean flag = parent.mkdirs();
            // ? 
            if (!flag) {
                log.error("File '" + file + "' could not be created");
                throw new IllegalArgumentException("File '" + file + "' could not be created");
            }
        }
    }
    return file;
}

From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Speichert den Kontoauszug im Dateisystem bzw. Messaging.
 * @param k der Kontoauszug. Er muss eine ID besitzen - also bereits gespeichert worden sein.
 * @param data die rohen Binaer-Daten.//from  w ww  . j a v a2s  .  co  m
 * @throws RemoteException
 * @throws ApplicationException
 */
public static void receive(Kontoauszug k, byte[] data) throws RemoteException, ApplicationException {
    if (k == null)
        throw new ApplicationException(i18n.tr("Kein Kontoauszug angegeben"));

    if (data == null || data.length == 0)
        throw new ApplicationException(i18n.tr("Kein Daten angegeben"));

    final Konto konto = k.getKonto();
    if (konto == null)
        throw new ApplicationException(i18n.tr("Kein Konto angegeben"));

    // Per Messaging speichern?
    if (MessagingAvailableConsumer.haveMessaging()
            && Boolean.parseBoolean(MetaKey.KONTOAUSZUG_STORE_MESSAGING.get(konto))) {
        QueryMessage qm = new QueryMessage(CHANNEL, data);
        Application.getMessagingFactory().getMessagingQueue("jameica.messaging.put").sendSyncMessage(qm);
        k.setUUID(qm.getData().toString());
        k.store();
        Logger.info("stored account statement data in messaging archive [id: " + k.getID() + ", uuid: "
                + k.getUUID() + "]");
        return;
    }

    // Im Dateisystem speichern
    String path = createPath(konto, k);
    try {
        File file = new File(path).getCanonicalFile();
        Logger.info("storing account statement data in file [id: " + k.getID() + ", file: " + file + "]");

        File dir = file.getParentFile();
        if (!dir.exists()) {
            Logger.info("auto-creating parent dir: " + dir);
            if (!dir.mkdirs())
                throw new ApplicationException(
                        i18n.tr("Erstellen des Ordners fehlgeschlagen. Ordner-Berechtigungen korrekt?"));
        }

        if (!dir.canWrite())
            throw new ApplicationException(i18n.tr("Kein Schreibzugriff in {0}", dir.toString()));

        OutputStream os = null;

        try {
            File target = file;

            int i = 0;
            while (i < 10000) {
                // Checken, ob die Datei schon existiert. Wenn ja, haengen wir einen Zaehler hinten drin.
                // Um sicherzugehen, dass wir die Datei nicht ueberschreiben.
                if (!target.exists())
                    break;

                // OK, die Datei gibts schon. Wir haengen den Counter hinten an
                i++;
                target = indexedFile(file, i);
            }
            os = new BufferedOutputStream(new FileOutputStream(target));
            os.write(data);
            k.setPfad(target.getParent());
            k.setDateiname(target.getName());
            k.store();
        } finally {
            IOUtil.close(os);
        }
    } catch (IOException e) {
        Logger.error("unable to store account statement data in file: " + path, e);
        throw new ApplicationException(
                i18n.tr("Speichern des Kontoauszuges fehlgeschlagen: {0}", e.getMessage()));
    }
}