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.pmerienne.trident.state.cassandra.embedded.AbstractEmbeddedServer.java

private void validateFolder(String folderPath) {
    String currentUser = System.getProperty("user.name");
    final File folder = new File(folderPath);
    if (!DEFAULT_TEST_FOLDERS.contains(folderPath)) {
        assert folder.exists() : String.format("Folder '%s' does not exist", folder.getAbsolutePath());
        assert folder.isDirectory() : String.format("Folder '%s' is not a directory", folder.getAbsolutePath());
        assert folder.canRead() : String
                .format("No read credential. Please grant read permission for the current" + " "
                        + "user '%s' on folder '%s'", currentUser, folder.getAbsolutePath());
        assert folder.canWrite() : String.format("No write credential. Please grant write permission for the "
                + "current " + "user '%s' on folder '%s'", currentUser, folder.getAbsolutePath());
    }//w w  w  .j  a  v a 2 s . c o  m
}

From source file:com.yobidrive.diskmap.buckets.BucketTableManager.java

private File getNextFile(File latestCommittedFile) throws NeedleManagerException {
    long fileNumber = -1;
    if (latestCommittedFile == null)
        fileNumber = 0L;//from   w w w . ja  v a 2  s . c  o  m
    else {
        // Verifies file name pattern and extracts file number
        int extIndex = latestCommittedFile.getName().indexOf(EXTENSION);
        if (extIndex <= 0)
            throw new BucketTableManagerException(
                    "Latest committed file has a wrong name: " + latestCommittedFile.getName());

        fileNumber = -1;
        String hexString = latestCommittedFile.getName().substring(0, extIndex);
        try {
            fileNumber = Long.parseLong(hexString, 16);
        } catch (Throwable th) {
            fileNumber = -1;
        }
        if (fileNumber < 0) {
            throw new BucketTableManagerException(
                    "Latest committed file has a negative index number: " + latestCommittedFile.getName());
        }
        fileNumber++; // Next!
    }

    File indexFile = getCreateFile(fileNumber, UEXTENSION);
    if (!indexFile.canRead() || !indexFile.canWrite()) {
        throw new BucketTableManagerException(
                "No read/write access to new index file" + indexFile.getAbsolutePath());
    }
    return indexFile;
}

From source file:de.mendelson.comm.as2.server.AS2ServerProcessing.java

/**A client performed a download request
 *
 * @param session//from w ww  .  ja v  a  2  s.co  m
 * @param request
 */
private void processDownloadRequestFile(IoSession session, DownloadRequestFile request) {
    DownloadResponseFile response = null;
    if (request instanceof DownloadRequestFileLimited) {
        DownloadRequestFileLimited requestLimited = (DownloadRequestFileLimited) request;
        response = new DownloadResponseFileLimited(requestLimited);
        InputStream inStream = null;
        try {
            if (request.getFilename() == null) {
                throw new FileNotFoundException();
            }
            File downloadFile = new File(requestLimited.getFilename());
            response.setFullFilename(downloadFile.getAbsolutePath());
            response.setReadOnly(!downloadFile.canWrite());
            response.setSize(downloadFile.length());
            if (downloadFile.length() < requestLimited.getMaxSize()) {
                inStream = new FileInputStream(request.getFilename());
                response.setData(inStream);
                ((DownloadResponseFileLimited) response).setSizeExceeded(false);
            } else {
                ((DownloadResponseFileLimited) response).setSizeExceeded(true);
            }
        } catch (Exception e) {
            response.setException(e);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (Exception e) {
                    //nop
                }
            }
        }
    } else {
        response = new DownloadResponseFile(request);
        InputStream inStream = null;
        try {
            if (request.getFilename() == null) {
                throw new FileNotFoundException();
            }
            File downloadFile = new File(request.getFilename());
            response.setFullFilename(downloadFile.getAbsolutePath());
            response.setReadOnly(!downloadFile.canWrite());
            response.setSize(downloadFile.length());
            inStream = new FileInputStream(downloadFile);
            response.setData(inStream);
        } catch (IOException e) {
            response.setException(e);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (Exception e) {
                    //nop
                }
            }
        }
    }
    session.write(response);
}

From source file:jfs.sync.fileencrypted.PlainDirStorageAccess.java

@Override
public FileInfo getFileInfo(String rootPath, String relativePath) {
    FileInfo result = new FileInfo();
    File file = getFile(rootPath, relativePath);
    result.setName(file.getName());//www . j  a va 2s .com
    result.setPath(file.getPath());
    result.setDirectory(file.isDirectory());
    result.setExists(file.exists());
    result.setCanRead(true);
    result.setCanWrite(true);
    if (log.isDebugEnabled()) {
        log.debug("PlainDirStorageAccess.getFileInfo() " + result.getPath() + " e[" + result.isExists() + "] d["
                + result.isDirectory() + "]");
    } // if
    if (result.isExists()) {
        result.setCanRead(file.canRead());
        result.setCanWrite(file.canWrite());
        if (!result.isDirectory()) {
            result.setModificationDate(file.lastModified());
            result.setSize(-1);
        } else {
            result.setSize(0);
        } // if
    } else {
        if (log.isDebugEnabled()) {
            log.debug("PlainDirStorageAccess.getFileInfo() could not detect file for " + result.getPath());
        } // if
    } // if
    return result;
}

From source file:org.apereo.lap.services.output.CSVOutputHandler.java

@Override
public OutputResult writeOutput(Output output) {
    OutputResult result = new OutputResult(output);
    // make sure we can write the CSV
    File csv = new File(configuration.getOutputDirectory(), output.filename);
    boolean created;
    try {//from   w  ww  .  j a v a  2  s . c o m
        created = csv.createNewFile();
        if (logger.isDebugEnabled())
            logger.debug("CSV file created (" + created + "): " + csv.getAbsolutePath());
    } catch (IOException e) {
        throw new IllegalStateException("Exception creating CSV file: " + csv.getAbsolutePath() + ": " + e, e);
    }
    if (!created) { // created file is going to be a writeable file so no check needed
        if (csv.isFile() && csv.canRead() && csv.canWrite()) {
            // file exists and we can write to it
            if (logger.isDebugEnabled())
                logger.debug("CSV file is writeable: " + csv.getAbsolutePath());
        } else {
            throw new IllegalStateException("Cannot write to the CSV file: " + csv.getAbsolutePath());
        }
    }

    // make sure we can read from the temp data source
    try {
        int rows = storage.getTempJdbcTemplate().queryForObject(output.makeTempDBCheckSQL(), Integer.class);
        logger.info(
                "Preparing to output " + rows + " from temp table " + output.from + " to " + output.filename);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failure while trying to count the output data rows: " + output.makeTempDBCheckSQL());
    }

    Map<String, String> sourceToHeaderMap = output.makeSourceTargetMap();
    String selectSQL = output.makeTempDBSelectSQL();

    // fetch the data to write to CSV
    SqlRowSet rowSet;
    try {
        // for really large data we probably need to use http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/jdbc/core/RowCallbackHandler.html
        rowSet = storage.getTempJdbcTemplate().queryForRowSet(selectSQL);
    } catch (Exception e) {
        throw new RuntimeException("Failure while trying to retrieve the output data set: " + selectSQL);
    }

    // write data to the CSV file
    int lines = 0;
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(new BufferedWriter(new FileWriter(csv, true)));
        CSVWriter writer = new CSVWriter(pw);

        // write out the header
        writer.writeNext(sourceToHeaderMap.values().toArray(new String[sourceToHeaderMap.size()]));

        // write out the rows
        while (rowSet.next()) {
            String[] rowVals = new String[sourceToHeaderMap.size()];
            for (int i = 0; i < sourceToHeaderMap.size(); i++) {
                rowVals[i] = (rowSet.wasNull() ? null : rowSet.getString(i + 1));
            }
            writer.writeNext(rowVals);
        }

        IOUtils.closeQuietly(writer);
    } catch (Exception e) {
        throw new RuntimeException("Failure writing output to CSV (" + csv.getAbsolutePath() + "): " + e, e);
    } finally {
        IOUtils.closeQuietly(pw);
    }

    result.done(lines, null);
    return result;
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

/**
 * Fetches the sequences identified by their accession identifiers and saves them in the specified directory,
 * using the specified data format. The saved files are named 'id.ext', where 'id' is the original sequence 
 * accession identifier and 'ext' the file extension that matches the specified format.
 * @param ids - accession identifiers.//from w w  w.  j  a  va  2s  .  co m
 * @param directory - the directory where the files will be saved.
 * @param format - the format that will be used to store the files.
 */
public void saveNucleotides(final Set<String> ids, final File directory, final Format format) {
    checkState(ids != null && !ids.isEmpty(), "Uninitialized or invalid sequence ids");
    checkArgument(directory != null && (directory.isDirectory() || directory.mkdirs()) && directory.canWrite(),
            "Uninitialized or invalid directory");
    try {
        final int retstart = 0, retmax = MAX_RECORDS_FETCHED;
        final Iterable<List<String>> partitions = partition(ids, retmax);
        for (final List<String> chunk : partitions) {
            efetch(chunk, retstart, retmax, directory, format);
        }
    } catch (Exception e) {
        LOGGER.error("Saving nucleotide sequences failed", e);
    }
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

/**
 * Gets the publications identified by their PubMed identifiers (PMIDs) and saves them in the specified 
 * directory, using the specified data format. The saved files are named 'id.ext', where 'id' is the 
 * original PMID and 'ext' the file extension that matches the specified format.
 * @param ids//from  w  w  w  .  java2 s .c  o  m
 * @param directory
 * @param format
 */
public void savePublications(final Set<String> ids, final File directory, final Format format) {
    checkState(ids != null && !ids.isEmpty(), "Uninitialized or invalid sequence ids");
    checkArgument(directory != null && (directory.isDirectory() || directory.mkdirs()) && directory.canWrite(),
            "Uninitialized or invalid directory");
    try {
        final int retstart = 0, retmax = MAX_RECORDS_FETCHED;
        final Iterable<List<String>> partitions = partition(ids, retmax);
        for (final List<String> chunk : partitions) {
            efetch(chunk, retstart, retmax, directory, format);
        }
    } catch (Exception e) {
        LOGGER.error("Saving publication references failed", e);
    }
}

From source file:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? /*from  w  ww.j  av  a  2s.c  om*/
 * 
 * @return
 */
public String downMedia(String msgType, String media_id, String path) {
    String localFile = null;
    //      SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/");
    try {
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + getAccessToken()
                + "&media_id=" + media_id;
        // log.error(path);
        // ? ?
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        String xx = conn.getHeaderField("Content-disposition");
        try {
            log.debug("===? +==?==" + xx);
            if (xx == null) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                String result = null;
                while ((line = reader.readLine()) != null) {
                    if (result == null) {
                        result = line;
                    } else {
                        result += line;
                    }
                }
                System.out.println(result);
                JSONObject dataJson = JSONObject.parseObject(result);
                return dataJson.getString("errcode");
            }
        } catch (Exception e) {
        }
        if (conn.getResponseCode() == 200) {
            String Content_disposition = conn.getHeaderField("Content-disposition");
            InputStream inputStream = conn.getInputStream();
            // // ?
            // Long fileSize = conn.getContentLengthLong();
            //  +
            String savePath = path + "/" + msgType;
            // ??
            String fileName = StringUtil.getDateSimpleStr()
                    + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", "");
            // 
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            // ??
            if (!saveDirFile.canWrite()) {
                log.error("??");
                throw new Exception();
            }
            // System.out.println("------------------------------------------------");
            // ?
            File file = new File(saveDirFile + "/" + fileName);
            FileOutputStream outStream = new FileOutputStream(file);
            int len = -1;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outStream.write(b, 0, len);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
            // ?
            localFile = fileName;
        }
    } catch (Exception e) {
        log.error("? !", e);
    } finally {

    }
    return localFile;
}

From source file:de.ipbhalle.metfrag.main.CommandLineTool.java

/**
 * // www  . j  ava  2 s. c  o  m
 * check directory for existence etc.
 * 
 * @param filename
 * @param shouldBeReadable
 * @param shouldBeWriteable
 * @return
 */
public static boolean checkForDir(String filename, boolean shouldBeReadable, boolean shouldBeWriteable) {
    File file = new File(filename);
    if (!file.exists()) {
        System.out.println("Error: Can not access directory " + filename + ". Not found.");
        return false;
    } else if (!file.isDirectory()) {
        System.out.println("Error: Can not access directory " + filename + ". No Directory.");
        return false;
    } else if (shouldBeReadable && !file.canRead()) {
        System.out.println("Error: Can not read directory " + filename + ". No permissions.");
        return false;
    }
    if (shouldBeWriteable && !file.canWrite()) {
        System.out.println("Error: Can not write into directory " + filename + ". No permissions.");
        return false;
    }
    return true;
}

From source file:dsfixgui.configs.DSFConfiguration.java

public void exportDSFix(String path) {

    File toDir = new File(path);
    if (toDir.canWrite()) {

        toDir = new File(path + DSF_FOLDER);
        //Get the unaltered files from the resource folder
        File fromDir = new File(FILES_DIR + DSF_FOLDER);

        try {// w w w.  j ava2  s . c  o m
            FileUtils.copyDirectory(fromDir, toDir);
        } catch (IOException ex) {
            ui.printConsole(EXPORT_FAILED);
            return;
        }

        toDir = new File(path + DSF_FOLDER + "\\" + DSF_FILES[1]);
        if (toDir.exists()) {
            ui.printConsole(DSF_FILES_COPIED);
            writeSettingsToIniFile(toDir.getPath());
        } else {
            ui.printConsole(EXPORT_FAILED);
            return;
        }

    } else {
        //Can't write to the directory
        ui.printConsole(CANT_WRITE_DIR);
        ui.printConsole(EXPORT_FAILED);
    }
}