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:jhttpp2.Jhttpp2Launcher.java

@SuppressWarnings("unchecked")
public void restoreSettings()// throws Exception
{
    if (server.getServerProperties() == null) {
        log.warn("server propertie where not set will not save them");
        return;/*from w  w w. ja  v  a2  s .  c  o m*/
    }

    try {

        // Restore the WildcardDioctionary and the URLActions with the
        // ObjectInputStream (settings.dat)...
        ObjectInputStream obj_in;
        File file = new File(DATA_FILE);
        if (!file.exists()) {
            if (!file.createNewFile() || !file.canWrite()) {
                log.warn("Can't create or write to file " + file.toString());
            } else
                saveServerSettings();
        }

        obj_in = new ObjectInputStream(new FileInputStream(file));
        server.setWildcardDictionary((WildcardDictionary) obj_in.readObject());
        server.setURLActions((List<OnURLAction>) obj_in.readObject());
        obj_in.close();
    } catch (IOException e) {
        log.warn("restoreSettings(): " + e.getMessage());
    } catch (ClassNotFoundException e_class_not_found) {
    }
}

From source file:com.gantzgulch.sharing.configuration.ApplicationContext.java

private File tryDirectory(String defaultStorageLocation) {
    System.out.println("Looking for storage location : trying : " + defaultStorageLocation);

    if (defaultStorageLocation == null) {
        return null;
    }//from ww w.  j  a va2  s.  c o  m

    File file = new File(defaultStorageLocation);
    file.mkdirs();
    return file.isDirectory() && file.canWrite() ? file : null;
}

From source file:com.citrix.g2w.webdriver.util.FileDownloader.java

public String downloader(String fileToDownloadLocation, String localDownloadPath)
        throws IOException, URISyntaxException {
    URL fileToDownload = new URL(fileToDownloadLocation);
    String fileNameURI = fileToDownload.getFile();
    String filePath = "";
    if (fileNameURI.contains("?")) {
        filePath = localDownloadPath/*from   w w w  .j a v  a2 s.c o m*/
                + fileNameURI.substring(fileNameURI.substring(0, fileNameURI.indexOf("?")).lastIndexOf("/") + 1,
                        fileNameURI.indexOf("?"));
    } else {
        filePath = localDownloadPath + fileNameURI.substring(fileNameURI.lastIndexOf("/") + 1);
    }
    File downloadedFile = new File(filePath);
    if (downloadedFile.canWrite() == false) {
        downloadedFile.setWritable(true);
    }

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                this.mimicCookieState(this.driver.manage().getCookies()));
    }

    HttpGet httpget = new HttpGet(fileToDownload.toURI());
    HttpParams httpRequestParameters = httpget.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    httpget.setParams(httpRequestParameters);

    HttpResponse response = client.execute(httpget, localContext);

    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    this.logger.log("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:com.erudika.para.storage.LocalFileStore.java

@Override
public String store(String path, InputStream data) {
    if (StringUtils.startsWith(path, File.separator)) {
        path = path.substring(1);/*from w  ww.  ja  v  a 2 s.co  m*/
    }
    if (StringUtils.isBlank(path)) {
        return null;
    }
    int maxFileSizeMBytes = Config.getConfigInt("para.localstorage.max_filesize_mb", 10);
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {
        if (data.available() > 0 && data.available() <= (maxFileSizeMBytes * 1024 * 1024)) {
            File f = new File(folder + File.separator + path);
            if (f.canWrite()) {
                fos = new FileOutputStream(f);
                bos = new BufferedOutputStream(fos);
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = data.read(bytes)) != -1) {
                    bos.write(bytes, 0, read);
                }
                return f.getAbsolutePath();
            }
        }
    } catch (IOException e) {
        logger.error(null, e);
    } finally {
        try {
            fos.close();
            bos.close();
            data.close();
        } catch (IOException e) {
            logger.error(null, e);
        }
    }
    return null;
}

From source file:jfs.sync.encrypted.EncryptedFileStorageAccess.java

protected String filePermissionsString(File file) {
    return (file.canRead() ? "r" : "-") + (file.canWrite() ? "w" : "-") + (file.canExecute() ? "x" : "-");
}

From source file:it.geosolutions.tools.io.file.Copy.java

/**
 * Copy a list of files asynchronously to a destination (which can be on
 * nfs) each thread wait (at least) 'seconds' seconds for each file
 * propagation./*  w  w w  .  jav a2s  . com*/
 * 
 * @param ex
 *            the thread pool executor
 * @param baseDestDir
 * @param overwrite
 *            if false and destination exists() do not overwrite the file
 * @param seconds
 * @return the resulting moved file list or null
 * @note this function could not use overwrite boolean flag to avoid file
 *       lock on the same section when 2 thread are called to write the same
 *       file name
 */
public static List<FutureTask<File>> asynchCopyListFileToNFS(final ExecutorService ex, final List<File> list,
        final File baseDestDir, final int seconds) {
    // list
    if (list == null) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Failed to copy file list using a NULL list");
        return null;
    }
    final int size = list.size();
    if (size == 0) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Failed to copy file list using an empty list");
        return null;
    }
    // baseDestDir
    if (baseDestDir == null) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Failed to copy file list using a NULL baseDestDir");
        return null;
    } else if (!baseDestDir.isDirectory() || !baseDestDir.canWrite()) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Failed to copy file list using a not " + "writeable directory as baseDestDir: "
                    + baseDestDir.getAbsolutePath());
        return null;
    }
    // Asynch executor check
    if (ex == null || ex.isTerminated()) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Unable to run asynchronously using a terminated or null ThreadPoolExecutor");
        return null;
    }

    final List<FutureTask<File>> asyncRes = new ArrayList<FutureTask<File>>(size);
    for (File file : list) {
        if (file != null) {
            if (file.exists()) {
                try {
                    asyncRes.add(asynchFileCopyToNFS(ex, file, new File(baseDestDir, file.getName()), seconds));
                } catch (RejectedExecutionException e) {
                    if (LOGGER.isWarnEnabled())
                        LOGGER.warn("SKIPPING file:\n" + file.getAbsolutePath() + ".\nError: "
                                + e.getLocalizedMessage());
                } catch (IllegalArgumentException e) {
                    if (LOGGER.isWarnEnabled())
                        LOGGER.warn("SKIPPING file:\n" + file.getAbsolutePath() + ".\nError: "
                                + e.getLocalizedMessage());
                }

            } else {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn("SKIPPING file:\n" + file.getAbsolutePath()
                            + "\nUnable to copy a not existent file.");
            }
        }
    }

    return asyncRes;
}

From source file:MainClass.java

public Object[][] getFileStats(File dir) {
    String files[] = dir.list();/*from   w  w  w . j a  v a2 s .  c o m*/
    Object[][] results = new Object[files.length][titles.length];

    for (int i = 0; i < files.length; i++) {
        File tmp = new File(files[i]);
        results[i][0] = new Boolean(tmp.isDirectory());
        results[i][1] = tmp.getName();
        results[i][2] = new Boolean(tmp.canRead());
        results[i][3] = new Boolean(tmp.canWrite());
        results[i][4] = new Long(tmp.length());
        results[i][5] = new Date(tmp.lastModified());
    }
    return results;
}

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

private static void checkDirectory(String fileName, File file) throws EasyJaSubException {
    if (!file.isDirectory()) {
        throw new EasyJaSubException(fileName + " is not a directory");
    }//from  ww  w . j av a 2 s  . co  m
    if (!file.canRead()) {
        throw new EasyJaSubException("Directory " + fileName + " can not be read");
    }
    if (!file.canWrite()) {
        throw new EasyJaSubException("Directory " + fileName + " can not be written");
    }
}

From source file:com.github.fritaly.dualcommander.Utils.java

private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate,
        List<String> exclusionList) throws IOException {
    // recurse/*from   w  ww .j  av  a 2 s  . com*/
    File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
    if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs
        throw new IOException("Failed to list contents of " + srcDir);
    }
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (!destDir.mkdirs() && !destDir.isDirectory()) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    for (File srcFile : srcFiles) {
        File dstFile = new File(destDir, srcFile.getName());
        if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
            if (srcFile.isDirectory()) {
                doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
            } else {
                doCopyFile(srcFile, dstFile, preserveFileDate);
            }
        }
    }

    // Do this last, as the above has probably affected directory metadata
    if (preserveFileDate) {
        destDir.setLastModified(srcDir.lastModified());
    }
}

From source file:com.gft.cordova.plugins.trustdevice.TrustedDevicePlugin.java

/**
 * Check Write access in forbiden folders.
 *
 * @return true = have read access/*from w  ww  . jav  a2 s  .c o  m*/
 */
private boolean isWriteAccessViolation() {
    String[] foldersToCheckWriteAccess = { "/data", "/", "/system", "/system/bin", "/system/sbin",
            "/system/xbin", "/vendor/bin", "/sys", "/sbin", "/etc", "/proc", "/dev" };

    try {
        for (String folder : foldersToCheckWriteAccess) {
            File file = new File(folder);
            if (file.canWrite()) {
                return true;
            }
        }
    } catch (Exception e) {
    }
    return false;
}