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.dnielfe.manager.utils.SimpleUtils.java

/**
 * /*from  w  ww.  ja v a 2 s .  c  o m*/
 * @param old
 *            the file to be copied/ moved
 * @param newDir
 *            the directory to copy/move the file to
 */
public static void copyToDirectory(String old, String newDir) {
    File old_file = new File(old);
    File temp_dir = new File(newDir);
    byte[] data = new byte[BUFFER];
    int read = 0;

    if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String file_name = old.substring(old.lastIndexOf("/"), old.length());
        File cp_file = new File(newDir + file_name);

        try {
            BufferedOutputStream o_stream = new BufferedOutputStream(new FileOutputStream(cp_file));
            BufferedInputStream i_stream = new BufferedInputStream(new FileInputStream(old_file));

            while ((read = i_stream.read(data, 0, BUFFER)) != -1)
                o_stream.write(data, 0, read);

            o_stream.flush();
            i_stream.close();
            o_stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String files[] = old_file.list();
        String dir = newDir + old.substring(old.lastIndexOf("/"), old.length());
        int len = files.length;

        if (!new File(dir).mkdir())
            return;

        for (int i = 0; i < len; i++)
            copyToDirectory(old + "/" + files[i], dir);

    } else if (old_file.isFile() && !temp_dir.canWrite() && SimpleExplorer.rootAccess) {
        RootCommands.moveCopyRoot(old, newDir);
    } else if (!temp_dir.canWrite())
        return;

    return;
}

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

/**
 * Forces the deletion of the specified file. If the write property of the file to delete isn't
 * set, this property is then set before deleting.
 *
 * @param fileToDelete file to delete./* w  w  w .  ja  v  a2 s . c  om*/
 * @throws IOException if the deletion failed or if the file doesn't exist.
 */
public static void forceDeletion(File fileToDelete) throws IOException {
    if (fileToDelete.exists() && !fileToDelete.canWrite()) {
        fileToDelete.setWritable(true);
    }
    FileUtils.forceDelete(fileToDelete);
}

From source file:com.aoyetech.fee.commons.utils.FileUtils.java

public static FileOutputStream openOutputStream(final File file, final boolean append) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }/*  w w w.  j ava  2s  .  com*/
        if (file.canWrite() == false) {
            throw new IOException("File '" + file + "' cannot be written to");
        }
    } else {
        final File parent = file.getParentFile();
        if (parent != null) {
            if (!parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("Directory '" + parent + "' could not be created");
            }
        }
    }
    return new FileOutputStream(file, append);
}

From source file:eu.annocultor.utils.OntologySubtractor.java

private static void checkSrcAndDstDirs(File sourceDir, File destinationDir) throws Exception, IOException {

    if (!sourceDir.isDirectory()) {
        throw new Exception("Directory expected but this found: " + sourceDir.getCanonicalPath());
    }/*from ww  w  . j a va  2  s .c o m*/
    if (!destinationDir.isDirectory()) {
        throw new Exception("Directory expected but this found: " + destinationDir.getCanonicalPath());
    }
    if (!destinationDir.canWrite()) {
        throw new Exception("Directory is not writeable: " + destinationDir.getCanonicalPath());
    }
}

From source file:com.thalesgroup.hudson.plugins.klocwork.util.KloXMLGenerator.java

public static String GenerateXMLFromIssues(String a_host, String a_port, boolean useSSL, String a_projectname,
        String a_filename, BuildListener listener, String a_query, String a_user) {
    String kwurl = "";
    if (useSSL) {
        kwurl = "https://" + a_host + ":" + a_port;
    } else {/* w  ww . j  a  va  2 s .  c  o m*/
        kwurl = "http://" + a_host + ":" + a_port;
    }
    listener.getLogger().println("Connecting to Klocwork Web API service... " + kwurl);
    KWApi KWservice = new KWApi(kwurl);

    try {
        listener.getLogger().println("creating XML document");
        File outputFile = new File(a_filename);
        if (outputFile.exists()) {
            outputFile.delete();
        }
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(outputFile));
            if (outputFile.canWrite()) {
                //Get issues
                listener.getLogger().println("Retrieving Klocwork issues using kwjlib...");
                listener.getLogger()
                        .println("Sending request for project: " + a_projectname + " with query: " + a_query);
                ArrayList<JSONObject> issues = KWservice.search(a_projectname, a_query, null, null, null);
                if (issues != null) {
                    listener.getLogger().println("Number of issues returned: " + issues.size());
                    bw.write(
                            "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><errorList xmlns=\"http://www.klocwork.com/inForce/report/1.0\">");
                    //Iterate through issues
                    for (JSONObject issue : issues) {
                        if (issue != null) {
                            try {
                                if (issue.has("id") && issue.optString("id").length() > 0) {
                                    String id = StringEscapeUtils.escapeXml(issue.optString("id"));
                                    String file = StringEscapeUtils.escapeXml(issue.optString("file"));
                                    String method = StringEscapeUtils.escapeXml(issue.optString("method"));
                                    String code = StringEscapeUtils.escapeXml(issue.optString("code"));
                                    String message = StringEscapeUtils.escapeXml(issue.optString("message"));
                                    String status = StringEscapeUtils.escapeXml(issue.optString("status"));
                                    String state = StringEscapeUtils.escapeXml(issue.optString("state"));
                                    String owner = StringEscapeUtils.escapeXml(issue.optString("owner"));
                                    String severity = StringEscapeUtils.escapeXml(issue.optString("severity"));
                                    String severityCode = StringEscapeUtils
                                            .escapeXml(issue.optString("severityCode"));
                                    String taxonomyName = StringEscapeUtils
                                            .escapeXml(issue.optString("taxonomyName"));
                                    String url = StringEscapeUtils.escapeXml(issue.optString("url"));
                                    bw.write("<problem>");
                                    bw.newLine();
                                    bw.write("<problemID>" + id + "</problemID>");
                                    bw.newLine();
                                    bw.write("<file>" + file + "</file>");
                                    bw.newLine();
                                    bw.write("<method>" + method + "</method>");
                                    bw.newLine();
                                    bw.write("<code>" + code + "</code>");
                                    bw.newLine();
                                    bw.write("<message>" + message + "</message>");
                                    bw.newLine();
                                    bw.write("<citingStatus>" + status + "</citingStatus>");
                                    bw.newLine();
                                    bw.write("<state>" + state + "</state>");
                                    bw.newLine();
                                    bw.write("<owner>" + owner + "</owner>");
                                    bw.newLine();
                                    bw.write("<severity>" + severity + "</severity>");
                                    bw.newLine();
                                    bw.write("<severitylevel>" + severityCode + "</severitylevel>");
                                    bw.newLine();
                                    bw.write("<displayAs>" + severity + "</displayAs>");
                                    bw.newLine();
                                    bw.write("<taxonomies>");
                                    bw.newLine();
                                    bw.write("<taxonomy name=\"" + taxonomyName + "\" metaInf=\"\" />");
                                    bw.newLine();
                                    bw.write("</taxonomies>");
                                    bw.newLine();
                                    bw.write("<url>" + url + "</url>");
                                    bw.newLine();
                                    bw.write("</problem>");
                                    bw.newLine();
                                }
                            } catch (Exception e) {
                                listener.getLogger().println("[ERROR]: " + e.getMessage());
                                listener.getLogger().println("\tissue: " + issue.toString());
                                e.printStackTrace();
                            }
                        }
                    }
                    bw.write("</errorList>");
                } else {
                    listener.getLogger().println("ERROR: Unable to get issues from Klocwork server");
                    if (!KWservice.errorMessage.isEmpty()) {
                        for (JSONObject message : KWservice.errorMessage) {
                            listener.getLogger().println("\t" + message.toString());
                        }
                        KWservice.errorMessage.clear();
                    }
                    return "1";
                }
            } else {
                listener.getLogger()
                        .println("ERROR while generating XML. Could not open file for writing: " + a_filename);
            }
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
    } catch (IOException ioe) {
        listener.getLogger().println("ERROR while generating XML - IOException:" + ioe.getMessage());
        return "1";
    }
    File outputFile = new File(a_filename);
    if (outputFile.exists() && outputFile.length() > 0) {
        listener.getLogger().println("Creation of XML file complete. Closing connection to Web API.");
    } else {
        listener.getLogger().println(
                "Creation of XML file failed. You may have to run the kwauth command on your machine.");
    }
    return "0";
}

From source file:net.sf.firemox.tools.Picture.java

/**
 * Download a file from the specified URL to the specified local file.
 * /*from ww  w. j  a  v a 2s.c o  m*/
 * @param localFile
 *          is the new card's picture to try first
 * @param remoteFile
 *          is the URL where this picture will be downloaded in case of the
 *          specified card name has not been found locally.
 * @param listener
 *          the component waiting for this picture.
 * @since 0.83 Empty file are deleted to force file to be downloaded.
 */
public static synchronized void download(String localFile, URL remoteFile, MonitoredCheckContent listener) {
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    File toDownload = new File(localFile);
    if (toDownload.exists() && toDownload.length() == 0 && toDownload.canWrite()) {
        toDownload.delete();
    }
    if (!toDownload.exists() || (toDownload.length() == 0 && toDownload.canWrite())) {
        // the file has to be downloaded
        try {
            if ("file".equals(remoteFile.getProtocol())) {
                File localRemoteFile = MToolKit
                        .getFile(remoteFile.toString().substring(7).replaceAll("%20", " "), false);
                int contentLength = (int) localRemoteFile.length();
                Log.info("Copying from " + localRemoteFile.getAbsolutePath());
                LoaderConsole.beginTask(
                        LanguageManager.getString("downloading") + " " + localRemoteFile.getAbsolutePath() + "("
                                + FileUtils.byteCountToDisplaySize(contentLength) + ")");

                // Copy file
                in = new BufferedInputStream(new FileInputStream(localRemoteFile));
                byte[] buf = new byte[2048];
                int currentLength = 0;
                boolean succeed = false;
                for (int bufferLen = in.read(buf); bufferLen >= 0; bufferLen = in.read(buf)) {
                    if (!succeed) {
                        toDownload.getParentFile().mkdirs();
                        out = new BufferedOutputStream(new FileOutputStream(localFile));
                        succeed = true;
                    }
                    currentLength += bufferLen;
                    if (out != null) {
                        out.write(buf, 0, bufferLen);
                    }
                    if (listener != null) {
                        listener.updateProgress(contentLength, currentLength);
                    }
                }

                // Step 3: close streams
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                in = null;
                out = null;
                return;
            }

            // Testing mode?
            if (!MagicUIComponents.isUILoaded()) {
                return;
            }

            // Step 1: open streams
            final URLConnection connection = MToolKit.getHttpConnection(remoteFile);
            int contentLength = connection.getContentLength();
            in = new BufferedInputStream(connection.getInputStream());
            Log.info("Download from " + remoteFile + "(" + FileUtils.byteCountToDisplaySize(contentLength)
                    + ")");
            LoaderConsole.beginTask(LanguageManager.getString("downloading") + " " + remoteFile + "("
                    + FileUtils.byteCountToDisplaySize(contentLength) + ")");

            // Step 2: read and write until done
            byte[] buf = new byte[2048];
            int currentLength = 0;
            boolean succeed = false;
            for (int bufferLen = in.read(buf); bufferLen >= 0; bufferLen = in.read(buf)) {
                if (!succeed) {
                    toDownload.getParentFile().mkdirs();
                    out = new BufferedOutputStream(new FileOutputStream(localFile));
                    succeed = true;
                }
                currentLength += bufferLen;
                if (out != null) {
                    out.write(buf, 0, bufferLen);
                }
                if (listener != null) {
                    listener.updateProgress(contentLength, currentLength);
                }
            }

            // Step 3: close streams
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
            in = null;
            out = null;
            return;
        } catch (IOException e1) {
            if (MToolKit.getFile(localFile) != null) {
                MToolKit.getFile(localFile).delete();
            }
            if (remoteFile.getFile().equals(remoteFile.getFile().toLowerCase())) {
                Log.fatal("could not load picture " + localFile + " from URL " + remoteFile + ", "
                        + e1.getMessage());
            }
            String tmpRemote = remoteFile.toString().toLowerCase();
            try {
                download(localFile, new URL(tmpRemote), listener);
            } catch (MalformedURLException e) {
                Log.fatal("could not load picture " + localFile + " from URL " + tmpRemote + ", "
                        + e.getMessage());
            }
        }
    }
}

From source file:com.bjorsond.android.timeline.utilities.Utilities.java

public static void copyFile(String fromFile, String toPath, String toFilename) {

    System.out.println("COPY!");
    if (Environment.getExternalStorageState().equals("mounted")) {
        File sdCardDirectory = Environment.getExternalStorageDirectory();

        try {/*ww w  . ja va 2s  .  c o m*/
            if (sdCardDirectory.canWrite()) {

                File destinationDirectory = new File(toPath);
                File sourceFile = new File(fromFile);
                File destinationFile = new File(destinationDirectory, toFilename);

                if (!destinationDirectory.exists()) {
                    destinationDirectory.mkdirs();
                }

                FileChannel source = new FileInputStream(sourceFile).getChannel();
                FileChannel destination = new FileOutputStream(destinationFile).getChannel();
                destination.transferFrom(source, 0, source.size());
                source.close();
                destination.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:br.com.manish.ahy.kernel.util.FileUtil.java

public static void copyFile(String from, String to, Boolean overwrite) {

    try {/*  w  w  w  .j a  v a 2s .com*/
        File fromFile = new File(from);
        File toFile = new File(to);

        if (!fromFile.exists()) {
            throw new IOException("File not found: " + from);
        }
        if (!fromFile.isFile()) {
            throw new IOException("Can't copy directories: " + from);
        }
        if (!fromFile.canRead()) {
            throw new IOException("Can't read file: " + from);
        }

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

        if (toFile.exists() && !overwrite) {
            throw new IOException("File already exists.");
        } else {
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("Destination directory does not exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("Destination is not a valid directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("Can't write on destination: " + parent);
            }
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {

            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } finally {
            if (from != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
            if (to != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }

    } catch (Exception e) {
        throw new OopsException(e, "Problems when copying file.");
    }
}

From source file:com.chaschev.install.InstallMojo.java

private static boolean isWritable(File dir) {
    try {/*from w  w  w  . ja v  a2s . c  om*/
        File tempFile = File.createTempFile("testWrite", "txt", dir);
        if (tempFile.exists()) {
            tempFile.delete();
            return true;
        }
    } catch (IOException e) {
        return false;
    }

    return dir.canWrite();
}

From source file:com.microsoft.applicationinsights.internal.perfcounter.JniPCConnector.java

private static File buildDllLocalPath() {
    Properties properties = PropertyHelper.getSdkVersionProperties();
    if (properties == null) {
        throw new RuntimeException("Failed to find SDK Version Properties file.");
    }/*www .j  a  va  2 s  . co  m*/

    String version = properties.getProperty("version");
    if (version == null) {
        throw new RuntimeException("Failed to find SDK version.");
    }

    File dllPath = LocalFileSystemUtils.getTempDir();

    dllPath = new File(dllPath.toString(), AI_BASE_FOLDER);
    dllPath = new File(dllPath.toString(), AI_NATIVE_FOLDER);
    dllPath = new File(dllPath.toString(), version);

    if (!dllPath.exists()) {
        dllPath.mkdirs();
    }

    if (!dllPath.exists() || !dllPath.canRead() || !dllPath.canWrite()) {
        throw new RuntimeException("Failed to create a read/write folder for the native dll.");
    }

    InternalLogger.INSTANCE.trace("%s folder exists", dllPath.toString());

    return dllPath;
}