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.norconex.commons.lang.file.FileUtil.java

private static void assertFile(File file) throws IOException {
    if (file == null || !file.exists() || !file.isFile() || !file.canRead()) {
        throw new IOException("Not a valid file: " + file);
    }//from  w  ww .  j av a  2 s . com
}

From source file:hk.idv.kenson.jrconsole.Console.java

/**
 * Checking the param is ready to generate the report or not
 * @param params Parameters to be checked
 * @throws IllegalArgumentException The exception talking about the which argument is invalid
 *//*from  ww w  .  j a v  a  2 s.c o  m*/
private static void checkParam(Map<String, Object> params) throws IllegalArgumentException {
    log.debug("Checking runtime parameters...");
    //Checking the data-source
    if (params.get("source") == null)
        throw new IllegalArgumentException("Please specify the data-source");
    if (params.get("type") == null)
        params.put("type", "jdbc");
    String type = params.get("type").toString();
    if (!(type.equals("jdbc") || type.equals("json") || type.equals("xml") || type.equals("csv")))
        throw new IllegalArgumentException("type \"" + type + "\" is not supported");
    if (!("jdbc".equals(type) || !"pipe".equals(params.get("source")))) {
        File file = new File(params.get("source").toString());
        if (!(file.exists() && file.isFile()))
            throw new IllegalArgumentException("The source file is not exists: " + params.get("source"));
        if (!file.canRead())
            throw new IllegalArgumentException("The source file is not readable: " + params.get("source"));
    }

    //Checking the report template
    if (params.get("jrxml") == null && params.get("jasper") == null)
        throw new IllegalArgumentException("Please specify -jrxml or -jasper for loading report template");
    if (params.get("jrxml") != null) {
        File jrxml = new File(params.get("jrxml").toString());
        if (!jrxml.exists())
            throw new IllegalArgumentException("jrxml \"" + params.get("jrxml") + "\" is not exists");
        if (!jrxml.canRead())
            throw new IllegalArgumentException("jrxml \"" + params.get("jrxml") + "\" is not readable");
    }
    if (params.get("jasper") != null) {
        File jasper = new File(params.get("jasper").toString());
        if (!jasper.exists())
            throw new IllegalArgumentException("jasper \"" + params.get("jasper") + "\" is not exists");
        if (!jasper.canRead())
            throw new IllegalArgumentException("jasper \"" + params.get("jasper") + "\" is not readable");
    }

    //Checking output
    if (params.get("outputtype") == null)
        params.put("outputtype", "pdf");
    if (params.get("output") == null)
        params.put("output", System.getProperty("user.dir") + "/output.pdf");
    File output = new File(params.get("output").toString());
    if (output.exists() && !output.canWrite())
        throw new IllegalArgumentException("output \"" + params.get("output") + "\" cannot be overwrited");

    //Checking the locale and bundle
    try {
        if (params.get("locale") != null)
            params.put(PARAM_LOCALE, getLocale(params.remove("locale").toString()));
        if (params.get(PARAM_LOCALE) == null)
            params.put(PARAM_LOCALE, Locale.getDefault());
        if (params.get("bundle") != null)
            params.put(PARAM_BUNDLE, parseVal("bundle:" + params.get("bundle"), params));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error when reading properties/locale/resource-bundle", ex);
    }
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
 * Test file exists and is readable./*from  ww  w.j  a  va  2s .  co  m*/
 * @param f File to test.
 * @exception FileNotFoundException If file does not exist or is not unreadable.
 */
public static File assertReadable(final File f) throws FileNotFoundException {
    if (!f.exists()) {
        throw new FileNotFoundException(f.getAbsolutePath() + " does not exist.");
    }

    if (!f.canRead()) {
        throw new FileNotFoundException(f.getAbsolutePath() + " is not readable.");
    }

    return f;
}

From source file:ch.vorburger.mariadb4j.Util.java

/**
 * Retrieve the directory located at the given path. Checks that path indeed is a reabable
 * directory. If this does not exist, create it (and log having done so).
 * //  w  ww. ja v  a  2s .  c  o m
 * @param path directory(ies, can include parent directories) names, as forward slash ('/')
 *            separated String
 * @return safe File object representing that path name
 * @throws IllegalArgumentException If it is not a directory, or it is not readable
 */
public static File getDirectory(String path) {
    boolean log = false;
    File dir = new File(path);
    if (!dir.exists()) {
        log = true;
        try {
            FileUtils.forceMkdir(dir);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to create new directory at path: " + path, e);
        }
    }
    String absPath = dir.getAbsolutePath();
    if (absPath.trim().length() == 0) {
        throw new IllegalArgumentException(path + " is empty");
    }
    if (!dir.isDirectory()) {
        throw new IllegalArgumentException(path + " is not a directory");
    }
    if (!dir.canRead()) {
        throw new IllegalArgumentException(path + " is not a readable directory");
    }
    if (log) {
        logger.info("Created directory: " + absPath);
    }
    return dir;
}

From source file:com.xse.optstack.persconftool.base.persistence.PersConfImport.java

private static boolean handleDefaultDataEntry(final File defaultDataFile, final int featureId,
        final Map<String, EResource> resources, final EApplication application) {
    boolean hasWarnings = false;

    if (defaultDataFile.exists()) {
        if (defaultDataFile.canRead()) {
            final GsonBuilder gsonBuilder = new GsonBuilder();
            final Gson gson = gsonBuilder.create();
            try (final FileReader reader = new FileReader(defaultDataFile.getAbsolutePath())) {
                final JsonObject fromJson = gson.fromJson(reader, JsonObject.class);
                final JsonElement resourcesNode = fromJson.get(PersConfDefinitions.RESOURCES_KEY_NAME);
                if (resourcesNode != null) {
                    for (final Entry<String, JsonElement> entry : resourcesNode.getAsJsonObject().entrySet()) {
                        if (!resources.containsKey(entry.getKey())) {
                            Logger.warn(Activator.PLUGIN_ID,
                                    "No resource for config default data key '" + entry.getKey() + "' in "
                                            + defaultDataFile.getName() + " of application '"
                                            + application.getName() + "'.");
                            hasWarnings = true;
                            continue;
                        }//  w ww .  j  a  v  a2s.c  om
                        final EResource res = resources.get(entry.getKey());
                        final EDefaultData defaultData = (EDefaultData) res.getConfiguration()
                                .eGet(res.getConfiguration().eClass().getEStructuralFeature(featureId));
                        for (final Entry<String, JsonElement> configEntry : entry.getValue().getAsJsonObject()
                                .entrySet()) {
                            if (configEntry.getKey()
                                    .equals(PersconfPackage.Literals.EDEFAULT_DATA__SIZE.getName())) {
                                defaultData.setSize(configEntry.getValue().getAsString());
                            } else if (configEntry.getKey()
                                    .equals(PersconfPackage.Literals.EDEFAULT_DATA__DATA.getName())) {
                                defaultData.setData(configEntry.getValue().getAsString());
                            } else {
                                Logger.warn(Activator.PLUGIN_ID,
                                        "Unsupported config default data entry '" + configEntry.getKey()
                                                + "' in " + defaultDataFile.getName() + " of application '"
                                                + application.getName() + "'.");
                                hasWarnings = true;
                            }
                        }
                    }
                }
            } catch (final JsonSyntaxException e) {
                Logger.warn(Activator.PLUGIN_ID, "Invalid JSON syntax for " + defaultDataFile.getName()
                        + " of application '" + application.getName() + "'.", e);
                hasWarnings = true;
            } catch (final IOException | JsonIOException e) {
                Logger.warn(Activator.PLUGIN_ID, "Error reading default data configuration file "
                        + defaultDataFile.getName() + " of application '" + application.getName() + "'.", e);
                hasWarnings = true;
            }
        } else {
            Logger.warn(Activator.PLUGIN_ID, "Unable to read configurable default data from "
                    + defaultDataFile.getName() + " of application '" + application.getName() + "'.");
            hasWarnings = true;
        }
    }

    return hasWarnings;
}

From source file:br.com.autonomiccs.cloudTraces.main.CloudTracesSimulator.java

private static void validateInputFile(String[] args) {
    if (args.length != 1) {
        throw new GoogleTracesToCloudTracesException(
                "You should inform the full qualified path to the cloud traces data set.");
    }/*from  ww  w  . j a v a 2  s  .  c  o m*/
    File file = new File(args[0]);
    if (!file.exists()) {
        throw new GoogleTracesToCloudTracesException(String.format("File [%s] does not exist.", args[0]));
    }
    if (!file.canRead()) {
        throw new GoogleTracesToCloudTracesException(String.format("Cannot read file [%s] .", args[0]));
    }
}

From source file:eu.europeana.enrichment.common.Utils.java

public static List<File> expandFileTemplateFrom(File dir, String... pattern) throws IOException {
    List<File> files = new ArrayList<File>();

    for (String p : pattern) {

        File fdir = new File(new File(dir, FilenameUtils.getFullPathNoEndSeparator(p)).getCanonicalPath());
        if (!fdir.isDirectory())
            throw new IOException("Error: " + fdir.getCanonicalPath() + ", expanded from directory "
                    + dir.getCanonicalPath() + " and pattern " + p + " does not denote a directory");
        if (!fdir.canRead())
            throw new IOException("Error: " + fdir.getCanonicalPath() + " is not readable");
        FileFilter fileFilter = new WildcardFileFilter(FilenameUtils.getName(p));
        File[] list = fdir.listFiles(fileFilter);
        if (list == null)
            throw new IOException("Error: " + fdir.getCanonicalPath()
                    + " does not denote a directory or something else is wrong");
        if (list.length == 0)
            throw new IOException("Error: no files found, template " + p + " from dir " + dir.getCanonicalPath()
                    + " where we recognised " + fdir.getCanonicalPath() + " as path and " + fileFilter
                    + " as file mask");
        for (File file : list) {
            if (!file.exists()) {
                throw new FileNotFoundException(
                        "File not found: " + file + " resolved to " + file.getCanonicalPath());
            }/*from www .  j av  a 2s.c  om*/
        }
        files.addAll(Arrays.asList(list));
    }

    return files;
}

From source file:com.iksgmbh.sql.pojomemodb.utils.FileUtil.java

/**
 * Uses streams to perform copy//from  ww  w  .  j av  a  2s .  com
 * @param fromFile
 * @param toFile
 * @throws IOException
 */
public static void copyBinaryFile(final File fromFile, File toFile) {
    if (!fromFile.exists())
        throw new RuntimeException("FileCopy: " + "no such source file: " + fromFile.getAbsolutePath());
    if (!fromFile.isFile())
        throw new RuntimeException("FileCopy: " + "can't copy directory: " + fromFile.getAbsolutePath());
    if (!fromFile.canRead())
        throw new RuntimeException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsolutePath());

    if (toFile.isDirectory())
        toFile = new File(toFile, fromFile.getName());

    if (toFile.exists()) {
        if (!toFile.canWrite())
            throw new RuntimeException(
                    "FileCopy: " + "destination file is unwriteable: " + toFile.getAbsolutePath());
    } else {
        String parent = toFile.getParent();
        if (parent == null)
            parent = System.getProperty("user.dir");
        File dir = new File(parent);
        if (!dir.exists())
            throw new RuntimeException("FileCopy: " + "destination directory doesn't exist: " + parent);
        if (dir.isFile())
            throw new RuntimeException("FileCopy: " + "destination is not a directory: " + parent);
        if (!dir.canWrite())
            throw new RuntimeException("FileCopy: " + "destination directory is unwriteable: " + parent);
    }

    FileInputStream from = null;
    FileOutputStream to = null;
    try {
        from = new FileInputStream(fromFile);
        to = new FileOutputStream(toFile);
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = from.read(buffer)) != -1)
            to.write(buffer, 0, bytesRead); // write
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:edu.ur.file.db.FileSystemManager.java

/**
 * Add a file to the parent folder.  This copies the file
 * from it's current location.  The file must exist.   This
 * does not delete the file once the copy is complete.
 *
 * @param parent folder to add the file to
 * @param File to save /*from  w  w  w.j a  v a  2s.  c  om*/
 * @param uniqueName name in the file system to save the file to.
 * 
 * @return the information of the created file.
 * @throws IllegalFileSystemNameException 
 */
static DefaultFileInfo addFile(TreeFolderInfo parent, File file, String uniqueName)
        throws IllegalFileSystemNameException {
    DefaultFileInfo fileInfo = null;

    if (!file.isFile()) {
        throw new IllegalStateException("The file to add must be a file  " + file.getAbsolutePath());
    }

    if (!file.exists()) {
        throw new IllegalStateException("the file " + file.getAbsolutePath() + " does not exist ");
    }

    if (!file.canRead()) {
        throw new IllegalStateException("The file " + file.getAbsolutePath() + " cannot be read ");
    }

    File newFile = new File(parent.getFullPath() + uniqueName);

    try {
        fileInfo = new DefaultFileInfo();
        fileInfo.setFolderInfo(parent);
        fileInfo.setName(uniqueName);
        fileInfo.setModifiedDate(new Timestamp(new Date().getTime()));
        fileInfo.setCreatedDate(new Timestamp(new Date().getTime()));
        FileUtils.copyFile(file, newFile);
        fileInfo.setExists(true);
        fileInfo.setSize(newFile.length());

    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    return fileInfo;
}

From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java

public static File generateZipFile(List<File> files, String dirPath) {

    File dir_file = new File(dirPath);
    File zip_file = new File(dirPath + "/temp_" + (fileNum++) + ".zip");
    int dir_l = dir_file.getAbsolutePath().length();

    FileOutputStream fos = null;//  w  ww . j  a  v  a  2s  .c  om
    try {
        fos = new FileOutputStream(zip_file);
    } catch (FileNotFoundException e1) {
        log.warning("File not found", e1);
        return null;
    }

    ZipOutputStream zipout = new ZipOutputStream(fos);
    zipout.setLevel(1);
    for (int i = 0; i < files.size(); i++) {
        File f = (File) files.get(i);
        if (f.canRead()) {
            log.info("Adding file: " + f.getAbsolutePath());
            try {
                zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
            } catch (Exception e) {
                log.warning("Error adding to zip file", e);
                return null;
            }
            BufferedInputStream fr;
            try {
                fr = new BufferedInputStream(new FileInputStream(f));

                byte buffer[] = new byte[0xffff];
                int b;
                while ((b = fr.read(buffer)) != -1)
                    zipout.write(buffer, 0, b);

                fr.close();
                zipout.closeEntry();

            } catch (Exception e) {
                log.warning("Error closing zip file", e);
                return null;
            }
        }
    }

    try {
        zipout.finish();
        fos.flush();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    log.info("file zipped and returning as " + zip_file.getAbsolutePath());
    return zip_file;

}