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.ikon.util.ArchiveUtils.java

/**
 * Recursively create JAR archive from directory 
 *//*from   ww w  .  j a  va  2  s .  c  o 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");
}

From source file:dk.netarkivet.common.utils.XmlUtils.java

/** Read and parse an XML-file, and return
  * a Document object representing this object.
  * @param f a given xml file/*w  w  w.jav  a  2 s.c o  m*/
  * @return a Document representing the xml file
  * @throws IOFailure if unable to read the xml file
  *          or unable to parse the file as XML
  */
public static Document getXmlDoc(File f) throws IOFailure {
    ArgumentNotValid.checkNotNull(f, "File f");
    SAXReader reader = new SAXReader();
    if (!f.canRead()) {
        log.debug("Could not read file: '" + f + "'");
        throw new IOFailure("Could not read file: '" + f + "'");
    }

    try {
        return reader.read(f);
    } catch (DocumentException e) {
        log.warn("Could not parse the file as XML: '" + f + "'", e);
        throw new IOFailure("Could not parse the file as XML: '" + f + "'", e);
    }
}

From source file:net.sf.jsignpdf.Signer.java

/**
 * Sign the files//  ww  w .ja  va 2 s  . co m
 * 
 * @param anOpts
 */
private static void signFiles(SignerOptionsFromCmdLine anOpts) {
    final SignerLogic tmpLogic = new SignerLogic(anOpts);
    if (ArrayUtils.isEmpty(anOpts.getFiles())) {
        // we've used -lp (loadproperties) parameter
        if (!tmpLogic.signFile()) {
            exit(Constants.EXIT_CODE_ALL_SIG_FAILED);
        }
        return;
    }
    int successCount = 0;
    int failedCount = 0;

    for (final String wildcardPath : anOpts.getFiles()) {
        final File wildcardFile = new File(wildcardPath);

        File[] inputFiles;
        if (StringUtils.containsAny(wildcardFile.getName(), '*', '?')) {
            final File inputFolder = wildcardFile.getAbsoluteFile().getParentFile();
            final FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE,
                    new WildcardFileFilter(wildcardFile.getName()));
            inputFiles = inputFolder.listFiles(fileFilter);
            if (inputFiles == null) {
                continue;
            }
        } else {
            inputFiles = new File[] { wildcardFile };
        }
        for (File inputFile : inputFiles) {
            final String tmpInFile = inputFile.getPath();
            if (!inputFile.canRead()) {
                failedCount++;
                System.err.println(RES.get("file.notReadable", new String[] { tmpInFile }));
                continue;
            }
            anOpts.setInFile(tmpInFile);
            String tmpNameBase = inputFile.getName();
            String tmpSuffix = ".pdf";
            if (StringUtils.endsWithIgnoreCase(tmpNameBase, tmpSuffix)) {
                tmpSuffix = StringUtils.right(tmpNameBase, 4);
                tmpNameBase = StringUtils.left(tmpNameBase, tmpNameBase.length() - 4);
            }
            final StringBuilder tmpName = new StringBuilder(anOpts.getOutPath());
            tmpName.append(anOpts.getOutPrefix());
            tmpName.append(tmpNameBase).append(anOpts.getOutSuffix()).append(tmpSuffix);
            String outFile = anOpts.getOutFile();
            if (outFile == null)
                anOpts.setOutFile(tmpName.toString());
            if (tmpLogic.signFile()) {
                successCount++;
            } else {
                failedCount++;
            }

        }
    }
    if (failedCount > 0) {
        exit(successCount > 0 ? Constants.EXIT_CODE_SOME_SIG_FAILED : Constants.EXIT_CODE_ALL_SIG_FAILED);
    }
}

From source file:Main.java

private static InputStream createInputStream(String src) throws FileNotFoundException {
    if (src.startsWith(PREFIX_JAR)) {
        String name = src.substring(PREFIX_JAR.length());
        InputStream inputStream = Thread.currentThread().getClass().getResourceAsStream(name);
        if (inputStream == null) {
            throw new FileNotFoundException("resource not found: " + src);
        }//  w w w . ja  v a2  s .com
        return inputStream;
    } else if (src.startsWith(PREFIX_FILE)) {
        File file = new File(src.substring(PREFIX_FILE.length()));
        if (!file.exists()) {
            throw new IllegalArgumentException("file does not exist: " + src);
        } else if (!file.isFile()) {
            throw new IllegalArgumentException("not a file: " + src);
        } else if (!file.canRead()) {
            throw new IllegalArgumentException("cannot read file: " + src);
        }
        return new FileInputStream(file);
    }
    throw new IllegalArgumentException("invalid bitmap source: " + src);
}

From source file:adalid.commons.util.FilUtils.java

public static boolean isReadableFile(File file) {
    return file != null && file.isFile() && file.canRead();
}

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

/**
 * Create ZIP archive from file//from w w w  .ja  va  2 s  .c  o  m
 */
public static void createZip(File path, OutputStream os) throws IOException {
    log.debug("createZip({}, {})", new Object[] { path, 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");

        log.debug("FILE {}", path);
        ZipArchiveEntry zae = new ZipArchiveEntry(path.getName());
        zaos.putArchiveEntry(zae);
        FileInputStream fis = new FileInputStream(path);
        IOUtils.copy(fis, zaos);
        fis.close();
        zaos.closeArchiveEntry();

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

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

From source file:adalid.commons.util.FilUtils.java

public static boolean isReadableDirectory(File file) {
    return file != null && file.isDirectory() && file.canRead();
}

From source file:dk.statsbiblioteket.util.xml.XSLTTest.java

public static URL getURL(String resource) {
    if (resource == null) {
        return null;
    }/*ww w. java 2 s . co m*/
    try {
        return new URL(resource);
    } catch (MalformedURLException e) {
        // Nada error, just try the next
    }
    File file = new File(resource);
    if (file.exists() && file.canRead()) {
        try {
            return file.toURI().toURL();
        } catch (MalformedURLException e) {
            // Nada error, just try the next
        }
    }
    return Thread.currentThread().getContextClassLoader().getResource(resource);
}

From source file:com.tesora.dve.common.PEBaseTest.java

protected static File getFileFromLargeFileRepository(final String fileName)
        throws LargeTestResourceNotAvailableException {
    final String largeFileRepositoryPath = System.getProperty(LARGE_RESOURCE_DIR_VAR);
    if (largeFileRepositoryPath == null) {
        throw new LargeTestResourceNotAvailableException(
                "Environment variable '" + LARGE_RESOURCE_DIR_VAR + "' is undefined.");
    }/*from w w  w .  j  a v a 2  s  .com*/

    final File returnFile = new File(new File(largeFileRepositoryPath), fileName);
    if (!returnFile.canRead()) {
        throw new LargeTestResourceNotAvailableException(
                "The file '" + returnFile.getAbsolutePath() + "' is not accessible.");
    }

    return returnFile;
}

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

public static Object[][] getExcelData(String file, boolean headerRow, String sheetName) {
    Object[][] retobj = null;//from  www.  j  a v  a 2s. 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, headerRow);
        firstCol = getFirstCol(sheet);
        lastRow = sheet.getRows();
        colsCnt = sheet.getColumns();
        logger.info("Rows : " + lastRow);
        logger.info("Columns : " + colsCnt);
        retobj = new Object[lastRow - firstRow][colsCnt - firstCol];
        for (int row = firstRow; row < lastRow; row++) {
            Cell[] cells = sheet.getRow(row);
            for (int col = firstCol; col < cells.length; col++) {
                retobj[row - firstRow][col - firstCol] = cells[col].getContents();
            }
        }
    } 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;
}