Example usage for java.io File canRead

List of usage examples for java.io File canRead

Introduction

In this page you can find the example usage for java.io File canRead.

Prototype

public boolean canRead() 

Source Link

Document

Tests whether the application can read the file denoted by this abstract pathname.

Usage

From source file:org.psikeds.common.config.ConfigDirectoryHelper.java

/**
 * Look for a configuration file within the configuration directory.
 * //from  ww w. j a v a 2s  .c o  m
 * @param path
 *          name of the configuration file
 * @return File object if the config file exists and is readable;
 *         null otherwise
 */
static File resolveConfigFile(final String path) {
    File resolved = new File(resolveConfigDir(), path);
    LOGGER.debug("Configuration file resolved to {}", resolved.getAbsolutePath());
    if (!resolved.exists() || !resolved.isFile() || !resolved.canRead()) {
        LOGGER.warn("Configuration file {} does not exist or is not readable!", resolved.getAbsolutePath());
        resolved = null;
    }
    return resolved;
}

From source file:net.sourceforge.dita4publishers.tools.common.MapBosProcessorBase.java

/**
 * @param file/*from   ww  w.  j a  v  a  2  s  .  com*/
 */
private static void checkExistsAndCanRead(File file) {
    if (!file.exists()) {
        throw new RuntimeException("File " + file.getAbsolutePath() + " does not exist.");
    }
    if (!file.canRead()) {
        throw new RuntimeException("File " + file.getAbsolutePath() + " exists but cannot be read.");
    }
}

From source file:com.streamsets.datacollector.cluster.TarFileCreator.java

public static void createTarGz(File dir, File outputFile) throws IOException {
    Utils.checkState(dir.isDirectory(), Utils.formatL("Path {} is not a directory", dir));
    Utils.checkState(dir.canRead(), Utils.formatL("Directory {} cannot be read", dir));
    FileOutputStream dest = new FileOutputStream(outputFile);
    TarOutputStream out = new TarOutputStream(new BufferedOutputStream(new GZIPOutputStream(dest), 65536));
    File[] files = dir.listFiles();
    Utils.checkState(files != null, Utils.formatL("Directory {} could not be read", dir));
    Utils.checkState(files.length > 0, Utils.formatL("Directory {} is empty", dir));
    tarFolder(null, dir.getAbsolutePath(), out);
    out.close();//from  w  ww. ja  v a2 s .  c  o  m
}

From source file:com.myjeeva.poi.ExcelReader.java

private static OPCPackage getOPCPackage(File file) throws Exception {
    if (null == file || !file.canRead()) {
        throw new Exception("File object is null or cannot have read permission");
    }//from   w  w  w  .  j  a v a 2 s  .  com

    return OPCPackage.open(new FileInputStream(file));
}

From source file:com.p2p.peercds.cli.TorrentMain.java

public static String createTorrent(String directory, String fileName, String trackerURL) throws Exception {

    String response = null;/*from  w  w w. ja  v a2  s  .  com*/
    OutputStream fos = null;
    try {

        //Process the announce URLs into URIs
        List<URI> announceURIs = new ArrayList<URI>();
        //for (String url : announceURLs) { 
        announceURIs.add(new URI(trackerURL));
        //}

        //Create the announce-list as a list of lists of URIs
        //Assume all the URI's are first tier trackers
        List<List<URI>> announceList = new ArrayList<List<URI>>();
        announceList.add(announceURIs);

        File source = new File(directory + fileName);
        if (!source.exists() || !source.canRead()) {
            throw new IllegalArgumentException("Cannot access source file or directory " + source.getName());
        }

        //String[] filesnames = null;
        //filesnames = fileName.split("\\.(?=[^\\.]+$)");
        if (source.isFile()) {
            fileName = fileName.split("\\.(?=[^\\.]+$)")[0];
            fileName = fileName + ".torrent";
        } else {
            fileName = fileName + ".torrent";
        }

        fos = new FileOutputStream(directory + fileName);

        String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

        Torrent torrent = null;
        if (source.isDirectory()) {
            File[] files = source.listFiles(Constants.hiddenFilesFilter);
            Arrays.sort(files);
            torrent = Torrent.create(source, Arrays.asList(files), announceList, creator);
        } else {
            torrent = Torrent.create(source, announceList, creator);
        }

        torrent.save(fos);

        response = "true";

    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }

    return response;
}

From source file:android.databinding.tool.reflection.java.JavaAnalyzer.java

public static void initForTests() {
    String androidHome = loadAndroidHome();
    if (Strings.isNullOrEmpty(androidHome) || !new File(androidHome).exists()) {
        throw new IllegalStateException(
                "you need to have ANDROID_HOME set in your environment" + " to run compiler tests");
    }// w ww . j  ava2  s.  c o  m
    File androidJar = new File(androidHome + "/platforms/android-21/android.jar");
    if (!androidJar.exists() || !androidJar.canRead()) {
        throw new IllegalStateException("cannot find android jar at " + androidJar.getAbsolutePath());
    }
    // now load android data binding library as well

    try {
        ClassLoader classLoader = new URLClassLoader(new URL[] { androidJar.toURI().toURL() },
                ModelAnalyzer.class.getClassLoader());
        new JavaAnalyzer(classLoader);
    } catch (MalformedURLException e) {
        throw new RuntimeException("cannot create class loader", e);
    }

    SdkUtil.initialize(8, new File(androidHome));
}

From source file:cn.guoyukun.spring.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
        String displayName) throws IOException {
    File file = new File(filePath);

    if (StringUtils.isEmpty(displayName)) {
        displayName = file.getName();//from  w  w w  .  j  av a2  s.  com
    }

    if (!file.exists() || !file.canRead()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return;
    }

    String userAgent = request.getHeader("User-Agent");
    boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

    response.reset();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate, no-transform");
    response.setDateHeader("Expires", 0L);

    response.setContentType("application/x-download");
    response.setContentLength((int) file.length());

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    if (isIE) {
        displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
    } else {
        displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
    }
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:it.geosolutions.geobatch.catalog.file.GeoBatchDataDirAwarePropertyOverrideConfigurer.java

/**
 * Tries to find the provided properties file and then returns its properties.
 * /*w ww  .j  a v a2 s  .co  m*/
 * @param propertiesFile the {@link File} to load from. Must exists and be readable.
 * @throws IOException in case something bad happens trying to read the proeprties from the file.
 * 
 */
protected static Properties loadProperties(final File propertiesFile) throws IOException {
    // checks on provided file
    if (!(propertiesFile != null && propertiesFile.exists() && propertiesFile.isFile()
            && propertiesFile.canRead())) {
        return null;
    }
    // load the file
    InputStream is = null;
    try {
        is = new BufferedInputStream(new FileInputStream(propertiesFile));
        final Properties properties = new Properties();
        properties.load(is);
        return properties;
    } finally {
        // close
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(e.getLocalizedMessage(), e);
                }
            }
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.auth.identifier.common.IsBlacklisted.java

/**
 * Runs through .sparql files in the BLACKLIST_SPARQL_DIR.
 * //from ww  w .  jav a 2s.co  m
 * The first that returns one or more rows will be cause the user to be
 * blacklisted.
 * 
 * The first variable from the first solution set will be returned.
 */
private static String checkForBlacklisted(Individual ind, ServletContext context) {
    String realPath = context.getRealPath(BLACKLIST_SPARQL_DIR);
    File blacklistDir = new File(realPath);
    if (!blacklistDir.isDirectory() || !blacklistDir.canRead()) {
        log.debug("cannot read blacklist directory " + realPath);
        return NOT_BLACKLISTED;
    }

    log.debug("checking directlry " + realPath + " for blacklisting sparql query files");
    File[] files = blacklistDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".sparql");
        }
    });

    String reasonForBlacklist = NOT_BLACKLISTED;
    for (File file : files) {
        try {
            reasonForBlacklist = runSparqlFileForBlacklist(file, ind, context);
            if (reasonForBlacklist != NOT_BLACKLISTED)
                break;
        } catch (RuntimeException ex) {
            log.error("Could not run blacklist check query for file " + file.getAbsolutePath()
                    + File.separatorChar + file.getName(), ex);
        }
    }
    return reasonForBlacklist;
}

From source file:Main.java

/**
 * Indexes the given file using the given writer, or if a directory is given,
 * recurses over files and directories found under the given directory.
 * /*ww w  .  j  a v a 2 s  . c o m*/
 * NOTE: This method indexes one document per input file.  This is slow.  For good
 * throughput, put multiple documents into your input file(s).  An example of this is
 * in the benchmark module, which can create "line doc" files, one document per line,
 * using the
 * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
 * >WriteLineDocTask</a>.
 *  
 * @param writer Writer to the index where the given file/dir info will be stored
 * @param file The file to index, or the directory to recurse into to find files to index
 * @throws IOException If there is a low-level I/O error
 */
static void indexDocs(IndexWriter writer, File file) throws IOException {
    // do not try to index files that cannot be read
    if (file.canRead()) {
        if (file.isDirectory()) {
            String[] files = file.list();
            // an IO error could occur
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    indexDocs(writer, new File(file, files[i]));
                }
            }
        } else {

            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException fnfe) {
                // at least on windows, some temporary files raise this exception with an "access denied" message
                // checking if the file can be read doesn't help
                return;
            }

            try {

                // make a new, empty document
                Document doc = new Document();

                // Add the path of the file as a field named "path".  Use a
                // field that is indexed (i.e. searchable), but don't tokenize 
                // the field into separate words and don't index term frequency
                // or positional information:
                Field pathField = new StringField("path", file.getPath(), Field.Store.YES);
                doc.add(pathField);

                // Add the last modified date of the file a field named "modified".
                // Use a LongField that is indexed (i.e. efficiently filterable with
                // NumericRangeFilter).  This indexes to milli-second resolution, which
                // is often too fine.  You could instead create a number based on
                // year/month/day/hour/minutes/seconds, down the resolution you require.
                // For example the long value 2011021714 would mean
                // February 17, 2011, 2-3 PM.
                doc.add(new LongField("modified", file.lastModified(), Field.Store.NO));

                // Add the contents of the file to a field named "contents".  Specify a Reader,
                // so that the text of the file is tokenized and indexed, but not stored.
                // Note that FileReader expects the file to be in UTF-8 encoding.
                // If that's not the case searching for special characters will fail.
                doc.add(new TextField("contents",
                        new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8))));

                if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
                    // New index, so we just add the document (no old document can be there):
                    System.out.println("adding " + file);
                    writer.addDocument(doc);
                } else {
                    // Existing index (an old copy of this document may have been indexed) so 
                    // we use updateDocument instead to replace the old one matching the exact 
                    // path, if present:
                    System.out.println("updating " + file);
                    writer.updateDocument(new Term("path", file.getPath()), doc);
                }

            } finally {
                fis.close();
            }
        }
    }
}