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.rpgsheet.xcom.PimpMyXcom.java

public static Properties loadApplicationProperties() {
    String homePath = System.getProperty(SYSTEM_PROPERTY_USER_HOME);
    // verify that the home directory exists and can be read
    File homeDir = new File(homePath);
    if (homeDir.exists() == false) {
        log.error("Home directory '{}' does not exist.", homeDir.getAbsolutePath());
        return null;
    }/*from  w  ww . j  a v a  2  s . co m*/
    if (homeDir.canRead() == false) {
        log.error("Unable to read home directory '{}'.", homeDir.getAbsolutePath());
        return null;
    }
    // verify that the application properties file exists and can be read
    File appPropertiesFile = new File(homeDir, APPLICATION_PROPERTIES_FILE);
    try {
        createApplicationProperties(appPropertiesFile);
    } catch (IOException e) {
        log.error("Exception while creating application properties file.", e);
        return null;
    }
    // read the application properties from the disk
    Properties appProperties = new Properties();
    try {
        FileReader fileReader = new FileReader(appPropertiesFile);
        appProperties.load(fileReader);
    } catch (FileNotFoundException e) {
        log.error("Exception while trying to read application properties file.", e);
    } catch (IOException e) {
        log.error("Exception while trying to read application properties file.", e);
    }
    // return the read properties to the caller
    return appProperties;
}

From source file:io.janusproject.Boot.java

/** Parse the command line.
 *
 * @param args - the CLI arguments given to the program.
 * @param propertyFiles - files that may be filled with the filenames given on the CLI.
 * @return the arguments that are not recognized as CLI options.
 *///w  ww.ja  v  a  2 s  .c o m
public static String[] parseCommandLine(String[] args, List<URL> propertyFiles) {
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(getOptions(), args);
        parseCommandForInfoOptions(cmd);
        parseCommandLineForSystemProperties(cmd);
        parseCommandLineForVerbosity(cmd);
        // Retreive the list of the property files given on CLI
        if (cmd.hasOption('f')) {
            for (String rawFilename : cmd.getOptionValues('f')) {
                if (rawFilename == null || "".equals(rawFilename)) { //$NON-NLS-1$
                    showHelp();
                }
                File file = new File(rawFilename);
                if (!file.canRead()) {
                    //CHECKSTYLE:OFF
                    System.err.println(Locale.getString("INVALID_PROPERTY_FILENAME", //$NON-NLS-1$
                            rawFilename));
                    //CHECKSTYLE:ON
                    System.exit(ERROR_EXIT_CODE);
                }
                propertyFiles.add(file.toURI().toURL());
            }
        }
        return cmd.getArgs();
    } catch (IOException | ParseException e) {
        //CHECKSTYLE:OFF
        e.printStackTrace();
        //CHECKSTYLE:ON
        showHelp();
        // Only to avoid compilation errors
        throw new Error();
    }
}

From source file:es.ehu.si.ixa.pipe.nerc.train.InputOutputUtils.java

private static void checkInputFile(String name, File inFile) {

    String isFailure = null;//from ww  w  .  j  a v  a  2s .co m

    if (inFile.isDirectory()) {
        isFailure = "The " + name + " file is a directory!";
    } else if (!inFile.exists()) {
        isFailure = "The " + name + " file does not exist!";
    } else if (!inFile.canRead()) {
        isFailure = "No permissions to read the " + name + " file!";
    }

    if (null != isFailure) {
        throw new TerminateToolException(-1, isFailure + " Path: " + inFile.getAbsolutePath());
    }
}

From source file:net.sf.sripathi.ws.mock.util.Folder.java

/**
 * Gets the folder information for the path provided.
 * If the folder is not present creates a new folder.
 * /*from  w  w  w . j a  v  a  2s .c  o m*/
 * @param path folder path string.
 * 
 * @return instance of Folder class.
 */
public static Folder getInstance(String path) {

    Folder folder = null;
    Folder.folderMap = new HashMap<String, Folder>();
    Folder.fileSet = new TreeSet<String>();

    try {
        File file = new File(path);

        if (!file.exists()) {
            file.mkdir();
        }

        if (!file.isDirectory() && !file.canRead() && !file.canWrite()) {
            throw new MockException("Unable to read dir " + path + " make sure access is set correctly");
        }

        //Get root and sub directories
        folder = new Folder(path, file);

        Folder.folderMap.put(path, folder);

    } catch (Exception e) {
        throw new MockException("Unable to read dir " + path + " make sure access is set correctly");
    }

    return folder;
}

From source file:de.ingrid.iplug.csw.dsc.tools.FileUtils.java

/**
 * This function will copy files or directories from one location to another.
 * note that the source and the destination must be mutually exclusive. This 
 * function can not be used to copy a directory to a sub directory of itself.
 * The function will also have problems if the destination files already exist.
 * @param src -- A File object that represents the source for the copy
 * @param dest -- A File object that represnts the destination for the copy.
 * @throws IOException if unable to copy.
 * // www. j  a  v  a 2  s.c  o m
 * Source: http://www.dreamincode.net/code/snippet1443.htm
 */
public static void copyRecursive(File src, File dest) throws IOException {
    //Check to ensure that the source is valid...
    if (!src.exists()) {
        throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + ".");
    } else if (!src.canRead()) { //check to ensure we have rights to the source...
        throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + ".");
    }
    //is this a directory copy?
    if (src.isDirectory()) {
        if (!dest.exists()) { //does the destination already exist?
            //if not we need to make it exist if possible (note this is mkdirs not mkdir)
            if (!dest.mkdirs()) {
                throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + ".");
            }
        }
        //get a listing of files...
        String list[] = src.list();
        //copy all the files in the list.
        for (int i = 0; i < list.length; i++) {
            File dest1 = new File(dest, list[i]);
            File src1 = new File(src, list[i]);
            copyRecursive(src1, dest1);
        }
    } else {
        //This was not a directory, so lets just copy the file
        FileInputStream fin = null;
        FileOutputStream fout = null;
        byte[] buffer = new byte[4096]; //Buffer 4K at a time (you can change this).
        int bytesRead;
        try {
            //open the files for input and output
            fin = new FileInputStream(src);
            fout = new FileOutputStream(dest);
            //while bytesRead indicates a successful read, lets write...
            while ((bytesRead = fin.read(buffer)) >= 0) {
                fout.write(buffer, 0, bytesRead);
            }
            fin.close();
            fout.close();
            fin = null;
            fout = null;
        } catch (IOException e) { //Error copying file... 
            IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath()
                    + "to" + dest.getAbsolutePath() + ".");
            wrapper.initCause(e);
            wrapper.setStackTrace(e.getStackTrace());
            throw wrapper;
        } finally { //Ensure that the files are closed (if they were open).
            if (fin != null) {
                fin.close();
            }
            if (fout != null) {
                fin.close();
            }
        }
    }
}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

public static Response streamFile(String location, ServletContext context) {
    final File f = new File(location);
    if (!f.exists())
        return Response.status(Status.NOT_FOUND).build();
    if (!f.canRead())
        return Response.status(Status.FORBIDDEN).build();

    StreamingOutput stream = new StreamingOutput() {
        @Override/*from ww  w  .  j a  v a 2 s  .  c  o  m*/
        public void write(OutputStream os) throws IOException {
            try {
                if (f.isDirectory())
                    StorageHandler.streamDirectory(f, os);
                else
                    StorageHandler.streamFile(f, os);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    String filename = f.getName();
    String mime = context.getMimeType(f.getAbsolutePath());
    if (f.isDirectory()) {
        filename += ".zip";
        mime = "application/zip";
    }

    return Response.ok(stream, mime).header("content-disposition", "attachment; filename = " + filename)
            .build();
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

/**
 * @param submitIgnoreFile//from w  ww .ja v  a 2s .  co  m
 * @param ignorePatterns
 * @throws FileNotFoundException
 * @throws IOException
 */
private static void addIgnoredPatternsFromFile(File submitIgnoreFile, FilesToIgnore ignorePatterns)
        throws FileNotFoundException, IOException {
    if (submitIgnoreFile.canRead()) {
        BufferedReader ignoreContents = new BufferedReader(new FileReader(submitIgnoreFile));
        while (true) {
            String ignoreMe = ignoreContents.readLine();
            if (ignoreMe == null)
                break;
            ignorePatterns.addPattern(ignoreMe);
        }
        ignoreContents.close();
    }
}

From source file:com.vuze.plugin.azVPN_Helper.Checker_PIA.java

protected static String getDefaultUsername(PluginInterface pi) {
    try {//from w  w w. j av  a  2s .  c o m
        String pathPIAManager = pi.getPluginconfig().getPluginStringParameter(CONFIG_PIA_MANAGER_DIR);

        File pathPIAManagerData = new File(pathPIAManager, "data");

        // settings.json has the user name
        File fileSettings = new File(pathPIAManagerData, "settings.json");
        if (!fileSettings.isFile() || !fileSettings.canRead()) {
            return "";
        }
        String settingsText = FileUtil.readFileAsString(fileSettings, -1);
        Map<?, ?> mapSettings = JSONUtils.decodeJSON(settingsText);
        String user = (String) mapSettings.get("user");

        return user == null ? "" : user;
    } catch (Exception e) {
        return "";
    }
}

From source file:org.hawkular.agent.monitor.util.Util.java

/**
 * Tries to determine the system ID for the machine where this JVM is located.
 *
 * @return system ID or null if cannot determine
 *//*w ww . j a v  a 2  s  . c  om*/
public static String getSystemId() {
    if (systemId == null) {
        File machineIdFile = new File("/etc/machine-id");
        if (machineIdFile.exists() && machineIdFile.canRead()) {
            try (Reader reader = new InputStreamReader(new FileInputStream(machineIdFile))) {
                systemId = new BufferedReader(reader).lines().collect(Collectors.joining("\n"));
            } catch (IOException e) {
                log.errorf(e,
                        "/etc/machine-id exists and is readable, but exception was raised when reading it");
                systemId = "";
            }
        } else {
            log.errorf("/etc/machine-id does not exist or is unreadable");
            // for the future, we might want to check additional places and try different things
            systemId = "";
        }
    }

    return (systemId.isEmpty()) ? null : systemId;
}

From source file:gov.nih.nci.cagrid.introduce.servicetools.FilePersistenceHelper.java

/**
 * Ensures the directory specified exists, is readable and writeable. If the
 * directory does not exist it is created.
 * /*from   w w  w. j  a  v  a2 s  . com*/
 * @param dir
 *            the directory to create or check the permissions of
 * @throws IOException
 *             if failed to create the directory or if the directory exists
 *             but has invalid permissions.
 */
public static synchronized void createStorageDirectory(File dir) throws IOException {
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            throw new IOException("storDirFailed: " + dir);
        }
    } else {
        if (!dir.canWrite() || !dir.canRead()) {
            throw new IOException("storDirPerm: " + dir);
        }
    }
}