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.mfalaize.zipdiff.Main.java

private static void checkFile(java.io.File f) {
    String filename = f.toString();

    if (!f.exists()) {
        System.err.println("'" + filename + "' does not exist");
        System.exit(EXITCODE_ERROR);
    }//from  ww  w. j  a v a 2 s.  co m

    if (!f.canRead()) {
        System.err.println("'" + filename + "' is not readable");
        System.exit(EXITCODE_ERROR);
    }

    if (f.isDirectory()) {
        System.err.println("'" + filename + "' is a directory");
        System.exit(EXITCODE_ERROR);
    }

}

From source file:com.spotify.helios.cli.CliConfig.java

/**
 * Returns a CliConfig instance with values parsed from the specified file.
 *
 * If the file is not found, a CliConfig with pre-defined values will be returned.
 *
 * @param defaultsFile        The file to parse from
 * @throws IOException        If the file exists but could not be read
 * @throws URISyntaxException If a HELIOS_MASTER env var is present and doesn't parse as a URI
 *///from w w  w.jav  a 2  s . co m
public static CliConfig fromFile(File defaultsFile) throws IOException, URISyntaxException {
    final Map<String, Object> config;
    // TODO: use typesafe config for config file parsing
    if (defaultsFile.exists() && defaultsFile.canRead()) {
        config = Json.read(Files.readAllBytes(defaultsFile.toPath()), OBJECT_TYPE);
    } else {
        config = ImmutableMap.of();
    }
    return fromEnvVar(config);
}

From source file:it.jnrpe.server.JNRPEServer.java

/**
 * Loads the JNRPE configuration from the INI or the XML file.
 * //  ww  w. jav  a2 s  . c o  m
 * @param configurationFilePath
 *            The path to the configuration file
 * @return The parsed configuration.
 * @throws ConfigurationException
 *             -
 */
private static JNRPEConfiguration loadConfiguration(final String configurationFilePath)
        throws ConfigurationException {
    File confFile = new File(configurationFilePath);

    if (!confFile.exists() || !confFile.canRead()) {
        throw new ConfigurationException("Cannot access config file : " + configurationFilePath);
    }

    return JNRPEConfigurationFactory.createConfiguration(configurationFilePath);

}

From source file:com.bluemarsh.jswat.console.Main.java

/**
 * Find the startup file in one of several locations and by one
 * of several names, then run the commands found therein.
 *
 * @param  parser  the command interpreter.
 * @throws  IOException  if reading file fails.
 *//*from w  ww.  j a  v a  2 s . c  om*/
private static void runStartupFile(CommandParser parser, PrintWriter consoleOutput) throws IOException {
    File[] files = { new File(System.getProperty("user.dir"), ".jswatrc"),
            new File(System.getProperty("user.dir"), "jswat.ini"),
            new File(System.getProperty("user.home"), ".jswatrc"),
            new File(System.getProperty("user.home"), "jswat.ini") };
    for (File file : files) {
        if (file.canRead()) {
            consoleOutput.println("Executing startup file: " + file.getAbsolutePath());
            BufferedReader br = new BufferedReader(new FileReader(file));
            try {
                String line = br.readLine();
                while (line != null) {
                    line = line.trim();
                    if (!line.isEmpty() && !line.startsWith("#")) {
                        performCommand(consoleOutput, parser, line);
                    }
                    line = br.readLine();
                }
            } finally {
                br.close();
            }
            // We just read the first file we find and stop.
            break;
        }
    }
}

From source file:com.microsoft.tfs.core.externaltools.ExternalTool.java

/**
 * <p>/*from   ww  w  .  jav a2s.co  m*/
 * Given a path to an application bundle (ie, Mac ".app" directory),
 * determine the path to the bundled executable. For example, given
 * /Applications/Camino.app, return
 * /Applications/Camino.app/Contents/MacOS/Camino.
 * </p>
 *
 * @param appBundle
 *        path to the Mac .app bundle (must not be <code>null</code>)
 * @return the fully-qualified executable suitable for exec(), or null if
 *         the path is not a valid mac application bundle
 */
private static String getMacCommand(final String appBundle) {
    Check.notNull(appBundle, "appBundle"); //$NON-NLS-1$

    Map plistDict;
    final String plistPath = appBundle + "/Contents/Info.plist"; //$NON-NLS-1$

    final File plistFile = new File(plistPath);
    if (!plistFile.exists() || !plistFile.canRead()) {
        return null;
    }

    try {
        final FileInputStream plistStream = new FileInputStream(plistFile);

        final SAXParser plistParser = SAXUtils.newSAXParser();
        final PlistHandler plistHandler = new PlistHandler();
        plistParser.parse(plistStream, plistHandler);

        final Object plist = plistHandler.getPlist();

        if (!(plist instanceof Map)) {
            log.error(MessageFormat.format("Plist {0} does not contain dict", plistPath)); //$NON-NLS-1$
            return null;
        }

        plistDict = (Map) plist;
    } catch (final IOException e) {
        log.error(MessageFormat.format("Could not read plist {0}", plistPath), e); //$NON-NLS-1$
        return null;
    } catch (final ParserConfigurationException e) {
        log.error(MessageFormat.format("Could not parse plist {0}", plistPath), e); //$NON-NLS-1$
        return null;
    } catch (final SAXException e) {
        log.error(MessageFormat.format("Could not parse plist {0}", plistPath), e); //$NON-NLS-1$
        return null;
    }

    final Object executable = plistDict.get("CFBundleExecutable"); //$NON-NLS-1$
    if (executable == null || !(executable instanceof String)) {
        log.error(MessageFormat.format("Plist {0} contains no string entry for CFBundleExecutable", plistPath)); //$NON-NLS-1$
        return null;
    }

    return appBundle + "/Contents/MacOS/" + (String) executable; //$NON-NLS-1$
}

From source file:com.qmetry.qaf.automation.util.ExcelUtil.java

public static Object[][] getExcelDataAsMap(String file, String sheetName) {
    Object[][] retobj = null;//  w w w .j a  v  a  2 s. c om
    Workbook workbook = null;
    try {
        File f = new File(file);
        if (!f.exists() || !f.canRead()) {
            logger.error(" Can not read file " + f.getAbsolutePath() + " Returning empty dataset1");
            return new Object[][] {};
        }
        workbook = Workbook.getWorkbook(f);
        Sheet sheet = StringUtils.isNotBlank(sheetName) ? workbook.getSheet(sheetName) : workbook.getSheet(0);
        if (null == sheet) {
            throw new RuntimeException("Worksheet " + sheetName + " not found in " + f.getAbsolutePath());
        }
        int firstRow, firstCol, lastRow, colsCnt;
        firstRow = getFirstRow(sheet, false);
        firstCol = getFirstCol(sheet);
        lastRow = sheet.getRows();
        colsCnt = sheet.getColumns();
        String[] colNames = new String[colsCnt - firstCol];

        logger.info("Rows : " + lastRow);
        logger.info("Columns : " + colsCnt);
        retobj = new Object[lastRow - (firstRow + 1)][1]; // skipped header
        // row
        for (int row = firstRow; row < lastRow; row++) {
            Cell[] cells = sheet.getRow(row);
            if (row == firstRow) {
                for (int col = firstCol; col < (firstCol + cells.length); col++) {
                    colNames[col - firstCol] = cells[col].getContents().trim();
                }
            } else {
                HashMap<String, String> map = new HashMap<String, String>();
                for (int col = firstCol; col < (firstCol + cells.length); col++) {
                    map.put(colNames[col - firstCol], cells[col].getContents());
                }
                retobj[row - (firstRow + 1)][0] = map;
            }
        }

    } catch (Exception e) {
        logger.error("Error while fetching data from " + file, e);
        throw new DataProviderException("Error while fetching data from " + file, e);
    } finally {
        try {
            workbook.close();
        } catch (Exception e2) {
            // skip exception
        }
    }
    return retobj;

}

From source file:com.varaneckas.hawkscope.util.PathUtils.java

/**
 * Converts path separated with delimiter
 * @param path//from w  w  w  .ja  v  a2  s.c  o  m
 * @param delimiter
 * @return
 */
public static List<File> pathToDirList(final String path, final String delimiter) {
    if (path == null || path.equals("")) {
        return Collections.emptyList();
    }
    String[] locations = interpret(path).split(delimiter);
    final List<File> files = new ArrayList<File>();
    for (final String location : locations) {
        final File f = new File(unsanitizePath(location));
        if (!f.isDirectory()) {
            log.warn(f.getAbsolutePath() + " is not a directory!");
        } else if (!f.canRead()) {
            log.warn(f.getAbsolutePath() + " can not be read!");
        } else {
            files.add(f);
        }
    }
    locations = null;
    return files;
}

From source file:de.willuhn.jameica.hbci.io.csv.ProfileUtil.java

/**
 * Laedt die vorhandenen Profile fuer das Format.
 * @param format das Format.//from w  ww  . j  a  v a2s  . c om
 * @return die Liste der Profile.
 */
public static List<Profile> read(Format format) {
    List<Profile> result = new ArrayList<Profile>();

    if (format == null) {
        Logger.warn("no format given");
        Application.getMessagingFactory().sendMessage(
                new StatusBarMessage(i18n.tr("Kein Format ausgewhlt"), StatusBarMessage.TYPE_ERROR));
        return result;
    }

    final Profile dp = format.getDefaultProfile();
    result.add(dp); // System-Profil wird immer vorn einsortiert

    // 1. Mal schauen, ob wir gespeicherte Profil fuer das Format haben
    File dir = new File(Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath(),
            "csv");
    if (!dir.exists())
        return result;

    File file = new File(dir, format.getClass().getName() + ".xml");
    if (!file.exists() || !file.canRead())
        return result;

    Logger.info("reading csv profile " + file);
    XMLDecoder decoder = null;
    try {
        decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(file)));
        decoder.setExceptionListener(new ExceptionListener() {
            public void exceptionThrown(Exception e) {
                throw new RuntimeException(e);
            }
        });

        // Es ist tatsaechlich so, dass "readObject()" nicht etwa NULL liefert, wenn keine Objekte mehr in der
        // Datei sind sondern eine ArrayIndexOutOfBoundsException wirft.
        try {
            for (int i = 0; i < 1000; ++i) {
                Profile p = (Profile) decoder.readObject();
                // Migration aus der Zeit vor dem Support mulitpler Profile:
                // Da konnte der User nur das eine existierende Profil aendern, es wurde automatisch gespeichert
                // Das hatte gar keinen Namen. Falls also ein Profil ohne Name existiert (inzwischen koennen keine
                // mehr ohne Name gespeichert werden), dann ist es das vom User geaenderte Profil. Das machen wir
                // automatisch zum ersten User-spezifischen Profil
                if (StringUtils.trimToNull(p.getName()) == null) {
                    p.setName(dp.getName() + " 2");
                    p.setSystem(false);
                }
                result.add(p);
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            // EOF
        }

        Logger.info("read " + (result.size() - 1) + " profiles from " + file);
        Collections.sort(result);

        // Der User hat beim letzten Mal eventuell nicht alle Spalten zugeordnet.
        // Die wuerden jetzt hier in dem Objekt fehlen. Daher nehmen wir
        // noch die Spalten aus dem Default-Profil und haengen die fehlenden noch an.
    } catch (Exception e) {
        Logger.error("unable to read profile " + file, e);
        Application.getMessagingFactory().sendMessage(new StatusBarMessage(
                i18n.tr("Laden der Profile fehlgeschlagen: {0}", e.getMessage()), StatusBarMessage.TYPE_ERROR));
    } finally {
        if (decoder != null) {
            try {
                decoder.close();
            } catch (Exception e) {
                /* useless */}
        }
    }
    return result;
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory
 *//*w w w.j  a v a 2 s  .  com*/
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Recursively create JAR archive from directory
 *//*from   w ww.  jav a 2s .  co  m*/
public static void createJar(File path, String root, OutputStream os) throws IOException {
    log.debug("createJar({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        JarArchiveOutputStream jaos = new JarArchiveOutputStream(os);
        jaos.setComment("Generated by OpenKM");
        jaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        jaos.setUseLanguageEncodingFlag(true);
        jaos.setFallbackToUTF8(true);
        jaos.setEncoding("UTF-8");

        // Prevents java.util.jar.JarException: JAR file must have at least one entry
        JarArchiveEntry jae = new JarArchiveEntry(root + "/");
        jaos.putArchiveEntry(jae);
        jaos.closeArchiveEntry();

        createJarHelper(path, jaos, root);

        jaos.flush();
        jaos.finish();
        jaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createJar: void");
}