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.datos.vfs.provider.sftp.SftpClientFactory.java

private static void addIdentities(final JSch jsch, final File sshDir, final IdentityInfo[] identities)
        throws FileSystemException {
    if (identities != null) {
        for (final IdentityInfo info : identities) {
            addIndentity(jsch, info);/*from w w w  . j  av a  2 s.  co  m*/
        }
    } else {
        // Load the private key (rsa-key only)
        final File privateKeyFile = new File(sshDir, "id_rsa");
        if (privateKeyFile.isFile() && privateKeyFile.canRead()) {
            addIndentity(jsch, new IdentityInfo(privateKeyFile));
        }
    }
}

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

/** Gunzip a single gzipped file into the given file. Unlike with the gzip()
 * command-line tool, the original file is not deleted.
 *
 * @param fromFile A gzipped file to unzip.
 * @param toFile The file that the contents of fromFile should be gunzipped
 * into.  This file must be in an existing directory.  Existing contents of
 * this file will be overwritten.//  w w  w  . j  av a2  s. c  o m
 */
public static void gunzipFile(File fromFile, File toFile) {
    ArgumentNotValid.checkNotNull(fromFile, "File fromFile");
    ArgumentNotValid.checkTrue(fromFile.canRead(), "fromFile must be readable");
    ArgumentNotValid.checkNotNull(toFile, "File toFile");
    ArgumentNotValid.checkTrue(toFile.getAbsoluteFile().getParentFile().canWrite(),
            "toFile must be in a writeable dir");
    try {
        GZIPInputStream in = new LargeFileGZIPInputStream(new FileInputStream(fromFile));
        FileUtils.writeStreamToFile(in, toFile);
    } catch (IOException e) {
        throw new IOFailure("Error ungzipping '" + fromFile + "'", e);
    }
}

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

public static String[][] getTableData(String xlFilePath, String tableName, String sheetName) {
    String[][] tabArray = null;/*from   w  w w . j a v a  2  s . co  m*/
    Workbook workbook = null;
    try {
        File f = new File(xlFilePath);
        if (!f.exists() || !f.canRead()) {
            logger.error(" Can not read file " + f.getAbsolutePath() + " Returning empty dataset1");
            return new String[][] {};
        }
        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 startRow, startCol, endRow, endCol, ci, cj;
        Cell tableStart = sheet.findCell(tableName);
        if (null == tableStart) {
            throw new RuntimeException(
                    "Lable " + tableName + " for starting data range not found in sheet " + sheet.getName());
        }

        startRow = tableStart.getRow();
        startCol = tableStart.getColumn();
        Cell tableEnd = sheet.findCell(tableName, startCol + 1, startRow + 1, 100, 64000, false);
        if (null == tableEnd) {
            throw new RuntimeException(
                    "Lable " + tableName + " for ending data range not found in sheet " + sheet.getName());
        }
        endRow = tableEnd.getRow();
        endCol = tableEnd.getColumn();
        logger.debug("startRow=" + startRow + ", endRow=" + endRow + ", " + "startCol=" + startCol + ", endCol="
                + endCol);
        tabArray = new String[endRow - startRow - 1][endCol - startCol - 1];
        ci = 0;

        for (int i = startRow + 1; i < endRow; i++, ci++) {
            cj = 0;
            for (int j = startCol + 1; j < endCol; j++, cj++) {
                tabArray[ci][cj] = sheet.getCell(j, i).getContents();
            }
        }
    } catch (Exception e) {
        logger.error("error while fetching data from " + xlFilePath, e);
        throw new DataProviderException("Error while fetching data from " + xlFilePath, e);

    } finally {
        try {
            workbook.close();
        } catch (Exception e2) {
            // skip exception
        }
    }

    return (tabArray);
}

From source file:Main.java

public static boolean isCACertificateInstalled(File fileCA, String type, char[] password)
        throws KeyStoreException {

    KeyStore keyStoreCA = null;/*from   w ww .  j a  v  a 2  s.  c o  m*/
    try {
        keyStoreCA = KeyStore.getInstance(type/*, "BC"*/);
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (fileCA.exists() && fileCA.canRead()) {
        try {
            FileInputStream fileCert = new FileInputStream(fileCA);
            keyStoreCA.load(fileCert, password);
            fileCert.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (java.security.cert.CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration ex = keyStoreCA.aliases();
        Date exportFilename = null;
        String caAliasValue = "";

        while (ex.hasMoreElements()) {
            String is = (String) ex.nextElement();
            Date lastStoredDate = keyStoreCA.getCreationDate(is);
            if (exportFilename == null || lastStoredDate.after(exportFilename)) {
                exportFilename = lastStoredDate;
                caAliasValue = is;
            }
        }

        try {
            return keyStoreCA.getKey(caAliasValue, password) != null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:FileCopy.java

public static void copy(String fromFileName, String toFileName) throws IOException {
    File fromFile = new File(fromFileName);
    File toFile = new File(toFileName);

    if (!fromFile.exists())
        throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
    if (!fromFile.isFile())
        throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
    if (!fromFile.canRead())
        throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);

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

    if (toFile.exists()) {
        if (!toFile.canWrite())
            throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
        System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): ");
        System.out.flush();//from ww  w.ja  va 2  s  .  c  o m
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String response = in.readLine();
        if (!response.equals("Y") && !response.equals("y"))
            throw new IOException("FileCopy: " + "existing file was not overwritten.");
    } else {
        String parent = toFile.getParent();
        if (parent == null)
            parent = System.getProperty("user.dir");
        File dir = new File(parent);
        if (!dir.exists())
            throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
        if (dir.isFile())
            throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
        if (!dir.canWrite())
            throw new IOException("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
    } finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:com.docd.purefm.test.JavaFileTest.java

private static void testAgainstJavaIoFile(final JavaFile genericFile, final File javaFile) throws Throwable {
    assertEquals(javaFile, genericFile.toFile());
    assertEquals(javaFile.getName(), genericFile.getName());
    assertEquals(javaFile.getAbsolutePath(), genericFile.getAbsolutePath());
    assertEquals(javaFile.canRead(), genericFile.canRead());
    assertEquals(javaFile.canWrite(), genericFile.canWrite());
    assertEquals(javaFile.canExecute(), genericFile.canExecute());
    assertEquals(javaFile.exists(), genericFile.exists());
    assertEquals(javaFile.getPath(), genericFile.getPath());
    assertEquals(javaFile.getParent(), genericFile.getParent());
    assertEquals(javaFile.length(), genericFile.length());
    final File parentFile;
    final GenericFile genericParentFile = genericFile.getParentFile();
    if (genericParentFile == null) {
        parentFile = null;/*from   ww  w . j  a va  2 s  .com*/
    } else {
        parentFile = genericParentFile.toFile();
    }
    assertEquals(javaFile.getParentFile(), parentFile);
    assertEquals(javaFile.length(), genericFile.length());
    try {
        assertEquals(FileUtils.isSymlink(javaFile), genericFile.isSymlink());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        assertEquals(javaFile.getCanonicalPath(), genericFile.getCanonicalPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertEquals(javaFile.length(), genericFile.length());
    assertEquals(javaFile.lastModified(), genericFile.lastModified());
    assertEquals(javaFile.isDirectory(), genericFile.isDirectory());
    assertTrue(Arrays.equals(javaFile.list(), genericFile.list()));
    assertTrue(Arrays.equals(javaFile.listFiles(), genericFile.listFiles()));
}

From source file:com.sindicetech.siren.demo.loader.Loader.java

private static List<File> checkInputFilesAndFolders(String[] optionValues) {
    List<File> filesToProcess = new ArrayList<File>();
    for (String param : optionValues) {
        File fileOrDirectory = new File(param);
        if ((fileOrDirectory.isFile() || fileOrDirectory.isDirectory()) && fileOrDirectory.exists()
                && fileOrDirectory.canRead()) {
            filesToProcess.add(fileOrDirectory);
        } else {/* w w w  . ja va 2 s .  com*/
            logger.error("not existing or not readable file is skipped: {}", param);
        }
    }
    return filesToProcess;
}

From source file:de.rub.syssec.saaf.Headless.java

/**
 * Gather APKs for option-case fileList.
 * You can configure a optional fileList_prefix in saaf.conf.
 *
 * @param fileList  ASCI-file with multiple paths to APK-files
 * @return          LinkedList of APK-Files
 *///ww  w  .ja v  a  2s .  c o  m
private static LinkedList<File> gatherApksFromFileList(File fileList) {
    LinkedList<File> apks = new LinkedList<File>();
    String pathFileListPrefix = CONFIG.getConfigValue(ConfigKeys.FILE_LIST_PREFIX);
    if (pathFileListPrefix == null) {
        LOGGER.warn("No 'prefix' directory configured for fileList! If"
                + "you want to use it, add 'path_fileList_prefix' to" + "saaf.conf.");
        pathFileListPrefix = "";
    }
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(fileList));
        String line = null;
        while ((line = in.readLine()) != null) {
            /**
             * HACK: Every File produced by Microsoft SQL ... Studio,
             * starts with the non printable Bytes EF BB BF. This is
             * only a BugFix to destroy these bytes.
             * 
             * FIXME: Is this sequence on EACH line or only at the first?
             */
            byte[] a = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
            line = line.replaceAll(new String(a), "");

            File pathFileList = new File(pathFileListPrefix + File.separator
                    + line.replace("\\\\", "").replace("\\", File.separator));
            if (!pathFileList.isFile() || !pathFileList.canRead()) {
                LOGGER.error("Skipping non valid file: " + pathFileListPrefix);
            } else {
                apks.add(pathFileList);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception ignored) {
            }
        }
    }
    LOGGER.info("Read " + apks.size() + " files from FileList " + fileList);
    return apks;
}

From source file:com.lovejoy777sarootool.rootool.preview.IconPreview.java

private static void loadFromRes(final File file, final ImageView icon) {
    Drawable mimeIcon = null;// www.j ava2s. c o  m

    if (file != null && file.isDirectory()) {
        String[] files = file.list();
        if (file.canRead() && files != null && files.length > 0)
            mimeIcon = mResources.getDrawable(R.drawable.type_folder);
        else
            mimeIcon = mResources.getDrawable(R.drawable.type_folder_empty);
    } else if (file != null && file.isFile()) {
        final String fileExt = FilenameUtils.getExtension(file.getName());
        mimeIcon = mMimeTypeIconCache.get(fileExt);

        if (mimeIcon == null) {
            final int mimeIconId = MimeTypes.getIconForExt(fileExt);
            if (mimeIconId != 0) {
                mimeIcon = mResources.getDrawable(mimeIconId);
                mMimeTypeIconCache.put(fileExt, mimeIcon);
            }
        }
    }

    if (mimeIcon != null) {
        icon.setImageDrawable(mimeIcon);
    } else {
        // default icon
        icon.setImageResource(R.drawable.type_unknown);
    }
}

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

public static Object[][] getTableDataAsMap(String xlFilePath, String tableName, String sheetName) {
    Object[][] tabArray = null;/*from   ww  w  . jav a  2  s. co m*/
    Workbook workbook = null;
    try {
        File f = new File(xlFilePath);
        if (!f.exists() || !f.canRead()) {
            logger.error(" Can not read file " + f.getAbsolutePath() + " Returning empty dataset1");
            return new String[][] {};
        }
        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 startRow, startCol, endRow, endCol, ci, cj;
        Cell tableStart = sheet.findCell(tableName);
        if (null == tableStart) {
            throw new RuntimeException(
                    "Lable " + tableName + " for starting data range not found in sheet " + sheet.getName());
        }

        startRow = tableStart.getRow();
        startCol = tableStart.getColumn();
        Cell tableEnd = sheet.findCell(tableName, startCol + 1, startRow + 1, 100, 64000, false);
        if (null == tableEnd) {
            throw new RuntimeException(
                    "Lable " + tableName + " for ending data range not found in sheet " + sheet.getName());
        }
        endRow = tableEnd.getRow();
        endCol = tableEnd.getColumn();
        logger.debug("startRow=" + startRow + ", endRow=" + endRow + ", " + "startCol=" + startCol + ", endCol="
                + endCol);
        tabArray = new Object[endRow - startRow][1];
        ci = 0;
        String[] colNames = new String[endCol - startCol - 1];

        for (int i = startRow; i <= endRow; i++) {
            cj = 0;
            if (i == (startRow)) {
                for (int j = startCol + 1; j < endCol; j++, cj++) {
                    colNames[cj] = sheet.getCell(j, i).getContents().trim();
                    logger.debug("header[" + cj + "] : " + colNames[cj]);

                }
            } else {
                HashMap<String, String> map = new HashMap<String, String>();
                for (int j = startCol + 1; j < endCol; j++, cj++) {
                    map.put(colNames[cj], sheet.getCell(j, i).getContents());
                }
                logger.debug("Record " + ci + ":" + map);
                tabArray[ci++][0] = map;

            }
        }
    } catch (Exception e) {
        logger.error("error while fetching data from " + xlFilePath, e);
        throw new DataProviderException("Error while fetching data from " + xlFilePath, e);

    } finally {
        try {
            workbook.close();
        } catch (Exception e2) {
            // skip exception
        }
    }

    return (tabArray);
}