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:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Add a file to a ZIP archive.
 * @param zos The ZipOutputStream representing the ZIP archive.
 * @param file The File which is to be added to the ZIP archive.
 * @return True if adding succeeded./*  ww  w .  j a v  a 2 s . c  o m*/
 * @throws IOException Any exception when reading/writing data.
 */
private static boolean zipFile(final ZipOutputStream zos, final File file) throws IOException {
    if (!file.canRead()) {
        logger.error("zipFile can not read " + file.getCanonicalPath());
        return false;
    }
    zos.putNextEntry(new ZipEntry(file.getName()));
    FileInputStream fis = new FileInputStream(file);

    byte[] buffer = new byte[BUFFER_SIZE];
    int byteCount = 0;
    while ((byteCount = fis.read(buffer)) != -1) {
        zos.write(buffer, 0, byteCount);
    }
    fis.close();
    zos.closeEntry();
    return true;
}

From source file:com.floragunn.searchguard.test.helper.file.FileHelper.java

public static File getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) {
    File file = null;
    final URL fileUrl = AbstractSGUnitTest.class.getClassLoader().getResource(fileNameFromClasspath);
    if (fileUrl != null) {
        try {//  www.  j  a  va 2  s .  c  o m
            file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8"));
        } catch (final UnsupportedEncodingException e) {
            return null;
        }

        if (file.exists() && file.canRead()) {
            return file;
        } else {
            log.error("Cannot read from {}, maybe the file does not exists? ", file.getAbsolutePath());
        }

    } else {
        log.error("Failed to load " + fileNameFromClasspath);
    }
    return null;
}

From source file:com.microsoft.tfs.core.persistence.VersionedVendorFilesystemPersistenceStore.java

/**
 * Gets the local directory to store things in for the given vendor,
 * application, and version.//from   ww  w  . j  av a 2 s  .c  om
 *
 * @param vendorName
 *        the vendor name (must not be <code>null</code> or empty)
 * @param applicationName
 *        the application name (must not be <code>null</code> or empty)
 * @param version
 *        the version string (must not be <code>null</code> or empty)
 * @return the {@link File} for the constructed path, like
 *         "~/.vendorName/applicationName/version"
 */
private static File makeDirectoryForVendorApplicationVersion(final String vendorName,
        final String applicationName, final String version) {
    Check.notNullOrEmpty(vendorName, "vendorName"); //$NON-NLS-1$
    Check.notNullOrEmpty(applicationName, "applicationName"); //$NON-NLS-1$
    Check.notNullOrEmpty(version, "version"); //$NON-NLS-1$

    String path = PlatformMiscUtils.getInstance()
            .getEnvironmentVariable(EnvironmentVariables.TEE_PROFILE_DIRECTORY);

    if (path != null) {
        path = path.trim();
        try {
            if (StringUtil.isNullOrEmpty(path)) {
                log.warn(
                        "User specified profile location path is empty, TEE will use default profile location."); //$NON-NLS-1$
            } else if (!LocalPath.isPathRooted(path)) {
                log.warn("User specified location " //$NON-NLS-1$
                        + path + "is not an absolute path. TEE will use default profile location."); //$NON-NLS-1$
            } else {
                final File file = new File(path).getCanonicalFile();
                if (!file.exists()) {
                    file.mkdirs();
                }

                if (file.exists() && file.isDirectory() && file.canRead() && file.canWrite()) {
                    return file;
                } else {
                    log.warn("User specified location " //$NON-NLS-1$
                            + path + "can not be accessed. TEE will use default profile location."); //$NON-NLS-1$
                }
            }
        } catch (final IOException e) {
            log.error("Exception testing profile location specified by the user: " //$NON-NLS-1$
                    + path + ".\n" //$NON-NLS-1$
                    + "TEE will use the default profile location.", e); //$NON-NLS-1$
        }
    }

    if (Platform.isCurrentPlatform(Platform.WINDOWS)) {
        /*
         * Check to see if we can find the user's local application data
         * directory.
         */
        path = SpecialFolders.getLocalApplicationDataPath();
        if (path == null || path.length() == 0) {
            /*
             * If the user has never logged onto this box they will not have
             * a local application data directory. Check to see if they have
             * a roaming network directory that moves with them.
             */
            path = SpecialFolders.getApplicationDataPath();
            if (path == null || path.length() == 0) {
                /*
                 * The user does not have a roaming network directory
                 * either. Just place the cache in the common area.
                 */
                path = SpecialFolders.getCommonApplicationDataPath();
            }
        }

        // "C:\\Users\\[username]\\AppData\\Local\\Microsoft
        path = path + File.separator + vendorName;
    } else if (Platform.isCurrentPlatform(Platform.MAC_OS_X)) {
        // Use the user's Library directory, creating a vendor name
        // directory there.

        // "~/Library/Application Support/Microsoft"
        path = System.getProperty("user.home") //$NON-NLS-1$
                + File.separator + "Library" //$NON-NLS-1$
                + File.separator + "Application Support" //$NON-NLS-1$
                + File.separator + vendorName;
    } else {
        // Consider all other operating systems a normal variant of
        // Unix. We lowercase the path components because that's closer to
        // convention.

        // "~/.microsoft"
        path = System.getProperty("user.home") + File.separator + "." + vendorName.toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$
    }

    path = path + File.separator + applicationName + File.separator + version;

    log.debug(MessageFormat.format("Using path {0} for vendorName {1}, application {2}, and version {3}", //$NON-NLS-1$
            path, vendorName, applicationName, version));

    return new File(path);
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static String getFileIfCanRead(String path, String file) {
    File fileObj = new File(path, file);
    if (fileObj.canRead()) {
        return fileObj.getAbsoluteFile().getAbsolutePath();
    }//from  w  w w .j  a v a2  s .  c  o  m
    return null;
}

From source file:com.datatopia.clockwork.core.reportng.ReportNGUtils.java

/**
 * Determine if the given filename exists and is readable.
 * @param filename The file to check.//from   w ww .  ja  v  a2 s. co m
 * @return true if the file exists and is readable. If the filename is null,
 * then false is returned.
 */
public static boolean isReadable(String filename) {
    if (filename == null) {
        return false;
    }

    File file = new File(filename);
    return file.exists() && file.canRead();
}

From source file:com.dnielfe.manager.utils.SimpleUtils.java

private static void search_file(String dir, String fileName, ArrayList<String> n) {
    File root_dir = new File(dir);
    String[] list = root_dir.list();

    if (list != null && root_dir.canRead()) {
        int len = list.length;

        for (int i = 0; i < len; i++) {
            File check = new File(dir + "/" + list[i]);
            String name = check.getName();

            if (check.isFile() && name.toLowerCase().contains(fileName.toLowerCase())) {
                n.add(check.getPath());//from w  w w  .java2s .  c  o  m
            } else if (check.isDirectory()) {
                if (name.toLowerCase().contains(fileName.toLowerCase())) {
                    n.add(check.getPath());

                } else if (check.canRead() && !dir.equals("/"))
                    search_file(check.getAbsolutePath(), fileName, n);
            }
        }
    }
}

From source file:net.orpiske.ssps.common.repository.utils.RepositoryUtils.java

private static void readPackageProperties(final File file, final PackageInfo packageInfo) {
    File settingsFile = new File(file.getPath() + File.separator + "package.properties");

    if (logger.isDebugEnabled()) {
        logger.debug("Reading package properties for " + file.getPath());
        logger.debug("Trying to open package.properties at " + settingsFile.getPath());
    }/*  ww w. java2s .  c  o m*/

    if (settingsFile.exists() && settingsFile.canRead()) {
        PropertiesConfiguration packageSettings;
        try {
            packageSettings = new PropertiesConfiguration(settingsFile);

            String slot = packageSettings.getString("package.default.slot", SlotComparatorFactory.DEFAULT_SLOT);

            packageInfo.setSlot(slot);
        } catch (ConfigurationException e) {
            logger.warn("Unable to read package configuration file at " + settingsFile.getPath());

            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage(), e);
            }
        }
    } else {
        packageInfo.setSlot(SlotComparatorFactory.DEFAULT_SLOT);
    }

}

From source file:io.fabric8.agent.mvn.MavenSettingsImpl.java

private static URL safeGetFile(final String filePath) {
    if (filePath != null) {
        File file = new File(filePath);
        if (file.exists() && file.canRead() && file.isFile()) {
            try {
                return file.toURI().toURL();
            } catch (MalformedURLException e) {
                // do nothing
            }//  w ww .  j av  a  2  s  .co  m
        }
    }
    return null;
}

From source file:FileUtil.java

public static void copyFile(String from, String to, Boolean overwrite) {

    try {/*from  w  w w. ja  v  a2  s. co  m*/
        File fromFile = new File(from);
        File toFile = new File(to);

        if (!fromFile.exists()) {
            throw new IOException("File not found: " + from);
        }
        if (!fromFile.isFile()) {
            throw new IOException("Can't copy directories: " + from);
        }
        if (!fromFile.canRead()) {
            throw new IOException("Can't read file: " + from);
        }

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

        if (toFile.exists() && !overwrite) {
            throw new IOException("File already exists.");
        } else {
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("Destination directory does not exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("Destination is not a valid directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("Can't write on destination: " + parent);
            }
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {

            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } finally {
            if (from != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
            if (to != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
        }

    } catch (Exception e) {
        System.out.println("Problems when copying file.");
    }
}

From source file:com.grillecube.common.utils.JSONHelper.java

/**
 * return a String which contains the full file bytes
 * //w  w  w.j  av  a 2s.  c om
 * @throws IOException
 */
public static String readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("Couldnt read file. (It doesnt exists: " + file.getPath() + ")");
    }
    if (file.isDirectory()) {
        throw new IOException("Couldnt read file. (It is a directory!!! " + file.getPath() + ")");
    }
    if (!file.canRead() && !file.setReadable(true)) {
        throw new IOException("Couldnt read model file. (Missing read permissions: " + file.getPath() + ")");
    }

    byte[] encoded = Files.readAllBytes(Paths.get(file.getPath()));
    return (new String(encoded, StandardCharsets.UTF_8));
}