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:com.github.rnewson.couchdb.lucene.ConfigTest.java

@Test
public void testGetDir() {
    try {/*from  ww  w.  ja v  a2s  .  c  o  m*/
        final Config config = new Config();
        File dir = config.getDir();
        assertTrue(dir.exists());
        assertTrue(dir.canRead());
        assertTrue(dir.canWrite());
        assertEquals(new File("target", "indexes"), dir);
    } catch (ConfigurationException ce) {
        fail("ConfigurationException shouldn't have been thrown." + ce.getMessage());
    } catch (IOException ioe) {
        fail("IOException shouldn't have been thrown." + ioe.getMessage());
    }
}

From source file:com.cloudmine.api.BaseDeviceIdentifier.java

private void loadPropertiesFile(Properties properties) {
    File idFile = new File(PROPERTIES_FILE);
    if (idFile.exists() && idFile.isFile() && idFile.canRead()) {
        try {//w w  w.j av a2 s . com
            FileInputStream reader = new FileInputStream(idFile);
            properties.load(reader);
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }
}

From source file:foam.nanos.servlet.ImageServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // get path/*w w w. j  av  a2 s . c  om*/
    String cwd = System.getProperty("user.dir");
    String[] paths = getServletConfig().getInitParameter("paths").split(":");
    String reqPath = req.getRequestURI().replaceFirst("/?images/?", "/");

    // enumerate each file path
    for (int i = 0; i < paths.length; i++) {
        File src = new File(cwd + "/" + paths[i] + reqPath);
        if (src.isFile() && src.canRead()
                && src.getCanonicalPath().startsWith(new File(paths[i]).getCanonicalPath())) {
            String ext = EXTS.get(FilenameUtils.getExtension(src.getName()));
            try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(src))) {
                resp.setContentType(!SafetyUtil.isEmpty(ext) ? ext : DEFAULT_EXT);
                resp.setHeader("Content-Disposition",
                        "filename=\"" + StringEscapeUtils.escapeHtml4(src.getName()) + "\"");
                resp.setContentLengthLong(src.length());

                IOUtils.copy(is, resp.getOutputStream());
                return;
            }
        }
    }

    resp.sendError(resp.SC_NOT_FOUND);
}

From source file:MainClass.java

public Object[][] getFileStats(File dir) {
    String files[] = dir.list();/* www  .  ja v a  2  s.c  om*/
    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:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java

/**
 * @param file File to add.//from  w w  w  . j a v  a2s.  co  m
 * @param res Resulted collection.
 */
private static void addFile(File file, Map<String, List<File>> res) {
    if (file.isDirectory())
        return;

    if (!file.canRead()) {
        errorHelp("File can not be read: " + file.getAbsolutePath());

        return;
    }

    if (file.getName().endsWith(INPUT_FILE_EXTENSION)) {
        List<File> list = res.get(file.getName());

        if (list == null) {
            list = new ArrayList<>();

            res.put(file.getName(), list);
        }

        list.add(file);
    }
}

From source file:it.geosolutions.geobatch.catalog.dao.file.xstream.XStreamCatalogDAO.java

public CatalogConfiguration find(String id, boolean lock) throws IOException {
    InputStream inStream = null;/*w  ww.j a v a 2s . c  o  m*/
    try {
        final File entityfile = new File(getBaseDirectory(), id + ".xml");
        if (entityfile.canRead() && !entityfile.isDirectory()) {

            inStream = new FileInputStream(entityfile);
            XStream xstream = new XStream();
            alias.setAliases(xstream);
            FileBasedCatalogConfiguration obj = (FileBasedCatalogConfiguration) xstream.fromXML(inStream);
            if (obj.getWorkingDirectory() == null)
                obj.setWorkingDirectory(getBaseDirectory());
            if (LOGGER.isInfoEnabled())
                LOGGER.info("XStreamCatalogDAO:: FOUND " + id + ">" + obj + "<");
            return obj;

        }
    } catch (Exception e) {
        throw new IOException("Unable to load catalog config '" + id + "' from base dir " + getBaseDirectory(),
                e);
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    return null;
}

From source file:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java

/**
 * Creates a File for reading the JSON data.  The ".json" extension is added.
 * @param filepath the path/filename prefix
 * @param suffix the data suffix (without extension, e.g. ".json")
 * @return A File ready for reading, or null.
 *//*from  w  w  w  . j  av a2 s  .co m*/
protected static File createFileForReading(String filepath, String dataSuffix) {

    File w = new File(filepath + dataSuffix + ".json");
    if (!w.exists()) {
        return null;
    }

    if (!w.canRead()) {
        System.out.printf("Error, file:%s not readable.\n", filepath);
        return null;
    }

    return w;
}

From source file:edu.ehu.galan.lite.algorithms.ranked.supervised.tfidf.corpus.wikipedia.WikiCorpusStatistics.java

/**
 * Extracts statistics from a Wikipedia dump processed with wikiExtractor
 *
 * @param file - the root dir of the extracted files with WikiExtractor
 *//* w w w  .j  av a2  s .co  m*/
public void extractDirectory(File file) {
    // 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) {
                File[] listFiles = file.listFiles();
                for (int i = 0; i < file.listFiles().length; i++) {
                    if (listFiles[i] != null) {
                        extractDirectory2(listFiles[i]);
                    }
                }
            }
        }

    }
}

From source file:org.wso2.emm.agent.services.operation.OperationManager.java

public static String getOperationResponseFromLogcat(Context context, String logcat) throws IOException {
    File logcatFile = new File(logcat);
    if (logcatFile.exists() && logcatFile.canRead()) {
        DeviceInfo deviceInfo = new DeviceInfo(context);
        EventPayload eventPayload = new EventPayload();
        eventPayload.setPayload(logcat);
        eventPayload.setType("LOGCAT");
        eventPayload.setDeviceIdentifier(deviceInfo.getDeviceId());

        StringBuilder emmBuilder = new StringBuilder();
        StringBuilder publisherBuilder = new StringBuilder();
        int index = 0;
        String line;// w  w w.ja  v  a 2  s  .  c  o  m
        ReversedLinesFileReader reversedLinesFileReader = new ReversedLinesFileReader(logcatFile,
                Charset.forName("US-ASCII"));
        while ((line = reversedLinesFileReader.readLine()) != null) {
            publisherBuilder.insert(0, "\n");
            publisherBuilder.insert(0, line);
            //OPERATION_RESPONSE filed in the DM_DEVICE_OPERATION_RESPONSE is declared as a blob and hence can only hold 64Kb.
            //So we don't want to throw exceptions in the server. Limiting the response in here to limit the server traffic also.
            if (emmBuilder.length() < Character.MAX_VALUE - 8192) { //Keeping 8kB for rest of the response payload.
                emmBuilder.insert(0, "\n");
                emmBuilder.insert(0, line);
            }
            if (++index >= Constants.LogPublisher.NUMBER_OF_LOG_LINES) {
                break;
            }
        }
        LogPublisherFactory publisher = new LogPublisherFactory(context);
        if (publisher.getLogPublisher() != null) {
            eventPayload.setPayload(publisherBuilder.toString());
            publisher.getLogPublisher().publish(eventPayload);
            if (Constants.DEBUG_MODE_ENABLED) {
                Log.d(TAG, "Logcat published size: " + eventPayload.getPayload().length());
            }
        }
        eventPayload.setPayload(emmBuilder.toString());
        Gson logcatResponse = new Gson();
        logcatFile.delete();
        if (Constants.DEBUG_MODE_ENABLED) {
            Log.d(TAG, "Logcat payload size: " + eventPayload.getPayload().length());
        }
        return logcatResponse.toJson(eventPayload);
    } else {
        throw new IOException("Unable to find or read log file.");
    }
}

From source file:com.nesscomputing.config.util.FileConfigStrategy.java

@Override
public AbstractConfiguration load(final String configName, final String configPath)
        throws ConfigurationException {
    if (!(directoryLocation.exists() && directoryLocation.isDirectory() && directoryLocation.canRead())) {
        return null;
    }//  w ww . j ava  2s  . co  m
    // A property configuration lives in a configuration directory and is called
    // "config.properties"
    final File[] propertyFiles = new File[] {
            new File(directoryLocation, configPath + File.separator + "config.properties"),
            new File(directoryLocation, configName + ".properties") };

    for (final File propertyFile : propertyFiles) {
        if (propertyFile.exists() && propertyFile.isFile() && propertyFile.canRead()) {
            LOG.trace("Trying to load '%s'...", propertyFile);
            try {
                final AbstractConfiguration config = new PropertiesConfiguration(propertyFile);
                LOG.trace("... succeeded");
                return config;
            } catch (ConfigurationException ce) {
                LOG.trace("... failed", ce);
            }
        }
    }
    return null;
}