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:ibw.updater.common.config.ConfigurationLoader.java

/**
 * Loads configuration properties from a specified properties file and adds
 * them to the properties currently set. This method scans the <CODE>
 * CLASSPATH</CODE> for the properties file, it may be a plain file, but may
 * also be located in a zip or jar file. If the properties file contains a
 * property called <CODE>Configuration.Include</CODE>, the files specified
 * in that property will also be read. Multiple include files have to be
 * separated by spaces or colons.// ww  w  . ja v  a2 s  .co m
 * 
 * @param filename
 *            the properties file to be loaded
 * @throws ConfigurationException
 *             if the file can not be loaded
 */
private void loadFromFile(String filename) {
    File configProperties = new File(filename);
    InputStream input = null;
    try {
        if (configProperties.canRead()) {
            input = new FileInputStream(configProperties);
        } else {
            URL url = this.getClass().getResource("/" + filename);
            if (url == null) {
                throw new ConfigurationException("Could not find file or resource:" + filename);
            }
            input = url.openStream();
        }
        loadFromStream(input);
    } catch (IOException e) {
        throw new ConfigurationException("Could not load configuration from: " + filename, e);
    }
}

From source file:it.geosolutions.mariss.wps.ppio.OutputResourcesPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {

    ZipOutputStream zos = null;/*w  w w . jav a  2  s .c o  m*/
    try {
        OutputResource or = (OutputResource) value;

        zos = new ZipOutputStream(os);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        Iterator<File> iter = or.getDeletableResourcesIterator();
        while (iter.hasNext()) {

            File tmp = iter.next();
            if (!tmp.exists() || !tmp.canRead() || !tmp.canWrite()) {
                LOGGER.warning("Skip Deletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

            if (!tmp.delete()) {
                LOGGER.warning("File '" + tmp.getName() + "' cannot be deleted...");
            }
        }
        iter = null;

        Iterator<File> iter2 = or.getUndeletableResourcesIterator();
        while (iter2.hasNext()) {

            File tmp = iter2.next();
            if (!tmp.exists() || !tmp.canRead()) {
                LOGGER.warning("Skip Undeletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

        }
    } finally {
        try {
            zos.close();
        } catch (IOException e) {
            LOGGER.severe(e.getMessage());
        }
    }
}

From source file:com.aurel.track.plugin.JavaScriptPathExtenderAction.java

/**'
 * Return the textual content of the js file row by row
 * By first creating/instantiating such a report configuration class the loader will search for <TRACKPLUS_HOME>/plugins/<pluginName>/<className>
 * pluginName is configured in getDirs and put as get parameter
 * className is automatically passed by Ext js loader mechanism to the path/URL mapping specified by Ext.Loader.setPath()
 * @return/*  w w  w.ja v a2 s  . c  om*/
 * @throws Exception
 */
@Override
public String execute() throws Exception {
    String tpHome = HandleHome.getTrackplus_Home();
    String jsDir = tpHome + File.separator + HandleHome.PLUGINS_DIR + File.separator + pluginDir
            + File.separator + "js";
    int parameterIndex = jsFile.indexOf("?");
    if (parameterIndex != -1) {
        //if caching is not disabled a timestamp parameter is added it should be removed from the file name because otherwise it will not be found on the disk
        jsFile = jsFile.substring(0, parameterIndex);
    }
    File file = new File(jsDir + jsFile);
    if (file != null && file.exists() && file.canRead()) {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new FileReader(file));
            while ((sCurrentLine = br.readLine()) != null) {
                sb.append(sCurrentLine);
            }
        } catch (IOException e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                LOGGER.error(ExceptionUtils.getStackTrace(ex));
            }
        }
        JSONUtility.encodeJSON(servletResponse, sb.toString());
    }
    return null;
}

From source file:org.o3project.pseudo.mf.lib.PseudoMfLib.java

private boolean checkFlie(final File file) {
    if (file.exists()) {
        if (file.isFile() && file.canRead()) {
            return true;
        }//from   w w w  .ja v  a 2s. co  m
    }
    return false;
}

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

/**
 * Check Read access in forbiden folders.
 *
 * @return true = have read access//www. jav  a 2  s.  c  o  m
 */
private boolean isReadAccessViolation() {

    String[] foldersToCheckReadAccess = { "/data" };
    try {
        for (String folder : foldersToCheckReadAccess) {
            File file = new File(folder);
            if (file.canRead()) {
                return true;
            }
        }
    } catch (Exception e) {
    }
    return false;
}

From source file:com.fusesource.forge.jmstest.config.SpringConfigHelper.java

public void setSpringConfigLocations(List<String> locations) {
    springConfigLocations = new ArrayList<String>();

    for (String location : locations) {
        System.err.println("location -> " + location);
        File f = new File(location);
        if (f.exists()) {
            if (f.canRead()) {
                if (f.isDirectory()) {
                    for (String fileName : f.list(new FilenameFilter() {
                        public boolean accept(File dir, String name) {
                            File candidate = new File(dir, name);
                            if (!candidate.isFile()) {
                                return false;
                            } else {
                                return name.endsWith(".xml");
                            }/*w  w  w. ja v  a2 s .  c o m*/
                        }
                    })) {
                        String absFileName = new File(f, fileName).getAbsolutePath();
                        log().info("Found xml file: " + absFileName);
                        springConfigLocations.add(absFileName);
                    }
                } else if (f.isFile()) {
                    if (location.endsWith(".xml")) {
                        String absFileName = f.getAbsolutePath();
                        log().info("Found xml file: " + absFileName);
                        springConfigLocations.add(absFileName);
                    }
                }
            }
        }
    }

    applicationContext = null;
}

From source file:com.intel.cosbench.driver.util.HashedFileInputStream.java

public HashedFileInputStream(File file, boolean hashCheck, HashUtil hashutil, long size)
        throws FileNotFoundException {
    super(size);//w w w  .  jav  a 2  s  .  co m
    if (!file.canRead()) {
        throw new FileNotFoundException("can not read from " + file.getName());
    }
    this.util = hashutil;
    this.fs = new FileInputStream(file);
    this.hashCheck = hashCheck;
    this.size = size;
    this.hashLen = this.util.getHashLen();
}

From source file:de.u808.simpleinquest.web.download.DownloadController.java

@Override
protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object commandObject,
        BindException bindException) throws Exception {

    DownloadCommand downloadCommand = (DownloadCommand) commandObject;
    TermQuery query = new TermQuery(new Term(Indexer.ID_FIELD_NAME, downloadCommand.getFileId()));
    Hits hits = indexSearchBean.getIndexSearcher().search(query);
    if (hits.length() > 0) {
        Hit hit = (Hit) hits.iterator().next();
        String filePath = hit.get(Indexer.PATH_FIELD_NAME);
        // String filePrefix =
        // hit.get(Indexer.FILE_FETCH_PREFIX_FIELD_NAME);
        // boolean blockDirectDownload =
        // Boolean.valueOf(hit.get(Indexer.PREVENT_DIRECT_DOWNLOAD_FIELD_NAME));

        // if(!blockDirectDownload && StringUtils.isEmpty(filePrefix)){
        File downloadFile = new File(filePath);
        if (downloadFile != null && downloadFile.canRead()) {
            handleDownload(response, downloadFile);
        } else {/* w  ww  .ja v  a2  s  . c  o m*/
            return this.handleError(response, downloadCommand, "download.file",
                    "error.download.cannotAccessFile");
        }
        /*
         * } else{
         * 
         * }
         */

    }
    return this.handleError(response, downloadCommand, "download.file",
            "error.download.noFileWithIdIsStoredInTheIndex");
}

From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java

public static int compare(File file1, File file2, boolean file2IsPartial) throws IOException {
    LOG.debug("Comparing " + file1 + " and " + file2);
    if (!file1.canRead() || !file2.canRead()) {
        return (file1.canRead() ? 1 : (file2.canRead() ? -1 : 0));
    }//from  w  w w  .  j av  a 2  s . co m

    InputStream fileIStream1 = new BufferedInputStream(new FileInputStream(file1));
    InputStream fileIStream2 = new BufferedInputStream(new FileInputStream(file2));

    int b1;
    int b2;
    do {
        b1 = fileIStream1.read();
        b2 = fileIStream2.read();
    } while ((b1 == b2) && (b1 != -1) && (b2 != -1));

    if (file2IsPartial && (b2 == -1)) {
        // file2 is a partial file and all existing bytes match, we're all good
        return 0;
    }

    return ((b1 < b2) ? -1 : ((b1 > b2) ? 1 : 0));
}

From source file:io.github.mzmine.modules.rawdata.rawdataimport.RawDataImportModule.java

@SuppressWarnings("null")
@Override/*from   w  w w  .  ja  va  2 s .c o  m*/
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
        @Nonnull Collection<Task<?>> tasks) {

    final List<File> fileNames = parameters.getParameter(RawDataImportParameters.fileNames).getValue();
    final String removePrefix = parameters.getParameter(RawDataImportParameters.removePrefix).getValue();
    final String removeSuffix = parameters.getParameter(RawDataImportParameters.removeSuffix).getValue();

    if (fileNames == null) {
        logger.warn("Raw data import module started with no filenames");
        return;
    }
    for (File fileName : fileNames) {

        if ((!fileName.exists()) || (!fileName.canRead())) {
            MZmineGUI.displayMessage("Cannot read file " + fileName);
            logger.warn("Cannot read file " + fileName);
            continue;
        }

        DataPointStore dataStore = DataPointStoreFactory.getTmpFileDataStore();

        RawDataFileImportMethod method = new RawDataFileImportMethod(fileName, dataStore);
        MSDKTask newTask = new MSDKTask("Importing raw data file", fileName.getName(), method);
        newTask.setOnSucceeded(e -> {
            RawDataFile rawDataFile = method.getResult();
            if (rawDataFile == null)
                return;

            // Remove common prefix
            if (!Strings.isNullOrEmpty(removePrefix)) {
                String name = rawDataFile.getName();
                if (name.startsWith(removePrefix))
                    name = name.substring(removePrefix.length());
                rawDataFile.setName(name);
            }

            // Remove common suffix
            if (!Strings.isNullOrEmpty(removeSuffix)) {
                String fileExtension = FilenameUtils.getExtension(fileName.getAbsolutePath());
                String suffix = removeSuffix;
                if (suffix.equals(".*"))
                    suffix = "." + fileExtension;
                String name = rawDataFile.getName();
                if (name.endsWith(suffix))
                    name = name.substring(0, name.length() - suffix.length());
                rawDataFile.setName(name);
            }

            project.addFile(rawDataFile);
        });
        tasks.add(newTask);

    }

}