Java Code Examples for java.io.File.canRead()

The following are Jave code examples for showing how to use canRead() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: ProjectRunnerImpl.java   View Source Code Vote up 7 votes
private static FileObject buildScript(String actionName, boolean forceCopy) throws IOException {
    URL script = locateScript(actionName);

    if (script == null) {
        return null;
    }

    URL thisClassSource = ProjectRunnerImpl.class.getProtectionDomain().getCodeSource().getLocation();
    File jarFile = FileUtil.archiveOrDirForURL(thisClassSource);
    File scriptFile = Places.getCacheSubfile("executor-snippets/" + actionName + ".xml");
    
    if (forceCopy || !scriptFile.canRead() || (jarFile != null && jarFile.lastModified() > scriptFile.lastModified())) {
        try {
            URLConnection connection = script.openConnection();
            FileObject target = FileUtil.createData(scriptFile);

            copyFile(connection, target);
            return target;
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
            return null;
        }
    }

    return FileUtil.toFileObject(scriptFile);
}
 
Example 2
Project: unity-obb-downloader   File: Helpers.java   View Source Code Vote up 7 votes
/**
 * Helper function to ascertain whether a file can be read.
 *
 * @param c the app/activity/service context
 * @param fileName the name (sans path) of the file to query
 * @return true if it does exist, false otherwise
 */
static public int getFileStatus(Context c, String fileName) {
    // the file may have been delivered by Play --- let's make sure
    // it's the size we expect
    File fileForNewFile = new File(Helpers.generateSaveFileName(c, fileName));
    int returnValue;
    if (fileForNewFile.exists()) {
        if (fileForNewFile.canRead()) {
            returnValue = FS_READABLE;
        } else {
            returnValue = FS_CANNOT_READ;
        }
    } else {
        returnValue = FS_DOES_NOT_EXIST;
    }
    return returnValue;
}
 
Example 3
Project: parabuild-ci   File: MyTreeNode.java   View Source Code Vote up 7 votes
/**
 * Gets size of this file object.
 */
public long getSize() {
    File file = getFile();

    if (!file.canRead()) {
        return 0;    
    }
  
    if (!isDirectory()) {
        return (file.length());
    }

    File[] children = file.listFiles();

    long size = 0;

    if (children != null) {
        for (int i = 0; i < children.length; ++i) {
            size += children[i].length();
        }
    }

    return size;
}
 
Example 4
Project: jdk8u-jdk   File: AdaptorBootstrap.java   View Source Code Vote up 7 votes
private static void checkAclFile(String aclFileName) {
    if (aclFileName == null || aclFileName.length()==0) {
        throw new AgentConfigurationError(SNMP_ACL_FILE_NOT_SET);
    }
    final File file = new File(aclFileName);
    if (!file.exists()) {
        throw new AgentConfigurationError(SNMP_ACL_FILE_NOT_FOUND, aclFileName);
    }
    if (!file.canRead()) {
        throw new AgentConfigurationError(SNMP_ACL_FILE_NOT_READABLE, aclFileName);
    }

    FileSystem fs = FileSystem.open();
    try {
        if (fs.supportsFileSecurity(file)) {
            if (!fs.isAccessUserOnly(file)) {
                throw new AgentConfigurationError(SNMP_ACL_FILE_ACCESS_NOT_RESTRICTED,
                    aclFileName);
            }
        }
    } catch (IOException e) {
        throw new AgentConfigurationError(SNMP_ACL_FILE_READ_FAILED, aclFileName);

    }
}
 
Example 5
Project: can4eve   File: Preferences.java   View Source Code Vote up 7 votes
/**
 * get an instance of the preferences
 * 
 * @return - the instance
 * @throws Exception
 */
public static Preferences getInstance() {
  if (instance == null) {
    File jsonFile = JsonAble.getJsonFile(Preferences.class.getSimpleName());
    if (jsonFile.canRead()) {
      JsonManager<Preferences> jmPreferences = new JsonManagerImpl<Preferences>(
          Preferences.class);
      try {
        instance = jmPreferences.fromJsonFile(jsonFile);
      } catch (Exception e) {
        ErrorHandler.handle(e);
      }
    }
    if (instance == null)
      instance = new Preferences();
  }
  return instance;
}
 
Example 6
Project: s-store   File: SnapshotDelete.java   View Source Code Vote up 6 votes
private final List<File> retrieveRelevantFiles(String filePath, String nonce) {
    final File path = new File(filePath);

    if (!path.exists()) {
        errorString = "Provided search path does not exist: " + filePath;
        return null;
    }

    if (!path.isDirectory()) {
        errorString = "Provided path exists but is not a directory: " + filePath;
        return null;
    }

    if (!path.canRead()) {
        if (!path.setReadable(true)) {
            errorString = "Provided path exists but is not readable: " + filePath;
            return null;
        }
    }

    if (!path.canWrite()) {
        if (!path.setWritable(true)) {
            errorString = "Provided path exists but is not writable: " + filePath;
            return null;
        }
    }

    return retrieveRelevantFiles(path, nonce);
}
 
Example 7
Project: Phoenix-for-VK   File: FileManagerFragment.java   View Source Code Vote up 6 votes
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        restoreFromSavedInstanceState(savedInstanceState);
    }

    setHasOptionsMenu(true);

    currentAction = getArguments().getInt(Extra.ACTION);

    showHiddenFilesAndDirs = getArguments().getBoolean(EXTRA_SHOW_CANNOT_READ, true);
    filterFileExtension = getArguments().getString(EXTRA_FILTER_EXTENSION);

    filter = (dir, filename) -> {
        File sel = new File(dir, filename);
        boolean showReadableFile = showHiddenFilesAndDirs || sel.canRead();
        // Filters based on whether the file is hidden or not
        if (currentAction == SELECT_DIRECTORY) {
            return sel.isDirectory() && showReadableFile;
        }

        if (currentAction == SELECT_FILE) {
            // If it is a file check the extension if provided
            if (sel.isFile() && filterFileExtension != null) {
                return showReadableFile && sel.getName().endsWith(filterFileExtension);
            }

            return (showReadableFile);
        }

        return true;
    };
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 9
Project: openjdk-jdk10   File: TestLogConfigurationDeadLockWithConf.java   View Source Code Vote up 5 votes
/**
 * This test will run both with and without a security manager.
 *
 * The test starts a number of threads that will call
 *     LogManager.readConfiguration() concurrently (ReadConf), then starts
 *     a number of threads that will create new loggers concurrently
 *     (AddLogger), and then two additional threads: one (Stopper) that
 *     will stop the test after 4secs (TIME ms), and one DeadlockDetector
 *     that will attempt to detect deadlocks.
 * If after 4secs no deadlock was detected and no exception was thrown
 * then the test is considered a success and passes.
 *
 * This procedure is done twice: once without a security manager and once
 * again with a security manager - which means the test takes ~8secs to
 * run.
 *
 * Note that 8sec may not be enough to detect issues if there are some.
 * This is a best effort test.
 *
 * @param args the command line arguments
 * @throws java.lang.Exception if the test fails.
 */
public static void main(String[] args) throws Exception {
    File config =  new File(System.getProperty("test.src", "."),
                    "deadlockconf.properties");
    if (!config.canRead()) {
        System.err.println("Can't read config file: test cannot execute.");
        System.err.println("Please check your test environment: ");
        System.err.println("\t -Dtest.src=" + System.getProperty("test.src", "."));
        System.err.println("\t config file is: " + config.getAbsolutePath());
        throw new RuntimeException("Can't read config file: "
            + config.getAbsolutePath());
    }

    System.setProperty("java.util.logging.config.file",
           config.getAbsolutePath());

    // test without security
    System.out.println("No security");
    test();

    // test with security
    System.out.println("\nWith security");
    Policy.setPolicy(new Policy() {
        @Override
        public boolean implies(ProtectionDomain domain, Permission permission) {
            if (super.implies(domain, permission)) return true;
            // System.out.println("Granting " + permission);
            return true; // all permissions
        }
    });
    System.setSecurityManager(new SecurityManager());
    test();
}
 
Example 10
Project: android-project-gallery   File: FileExplorerActivity.java   View Source Code Vote up 5 votes
private int _showDirectoryContents()
{
	File folder = new File(loadingPathname + "/");
	File[] childs = folder.listFiles();
	
	if ((childs == null) || (childs.length == 0))
	{
		if (folder.canRead())
		{
			return 1;
		}
		else
		{
			return 2;
		}
		
	}
	else
	{
		for (File child : childs)
		{
			if ((showPlainFiles) || (child.isDirectory()))
				iChilds.add(child);
		}
		
		if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("list_folders_first", true))
		{
			Collections.sort(iChilds, comparatorFoldersUp);
			foldersUp = true;
		}
		else
		{
			Collections.sort(iChilds, comparatorFoldersNotUp);
			foldersUp = false;
		}
		
		return 0;
	}
}
 
Example 11
Project: openjdk-jdk10   File: CustomSystemClassLoader.java   View Source Code Vote up 5 votes
private Class<?> defineFinderClass(String name)
    throws ClassNotFoundException {
    final Object obj = getClassLoadingLock(name);
    synchronized(obj) {
        if (finderClasses.get(name) != null) return finderClasses.get(name);
        if (testLoggerFinderClass == null) {
            // Hack: we  load testLoggerFinderClass to get its code source.
            //       we can't use this.getClass() since we are in the boot.
            testLoggerFinderClass = super.loadClass("LoggerFinderLoaderTest$TestLoggerFinder");
        }
        URL url = testLoggerFinderClass.getProtectionDomain().getCodeSource().getLocation();
        File file = new File(url.getPath(), name+".class");
        if (file.canRead()) {
            try {
                byte[] b = Files.readAllBytes(file.toPath());
                Permissions perms = new Permissions();
                perms.add(new AllPermission());
                Class<?> finderClass = defineClass(
                        name, b, 0, b.length, new ProtectionDomain(
                        this.getClass().getProtectionDomain().getCodeSource(),
                        perms));
                System.out.println("Loaded " + name);
                finderClasses.put(name, finderClass);
                return finderClass;
            } catch (Throwable ex) {
                ex.printStackTrace();
                throw new ClassNotFoundException(name, ex);
            }
        } else {
            throw new ClassNotFoundException(name,
                    new IOException(file.toPath() + ": can't read"));
        }
    }
}
 
Example 12
Project: Photato   File: ResizedImageGenerator.java   View Source Code Vote up 5 votes
private void initAndCleanOutdatedResizedPictures() {
    try {
        this.resizedPicturesSet.addAll(Files.list(this.resizedPicturesFolder).collect(Collectors.toSet()));
        Set<Path> toDeleteResizedPictures = new HashSet<>(this.resizedPicturesSet);

        Queue<Path> toExplore = new LinkedList<>();
        toExplore.add(this.rootFolder);
        while (!toExplore.isEmpty()) {
            File currentFolder = toExplore.remove().toFile();

            if (currentFolder.canRead() && !FileHelper.folderContainsIgnoreFile(currentFolder.toPath())) {
                File[] files = currentFolder.listFiles();

                if (files != null) {
                    for (File file : files) {
                        if (file.isDirectory()) {
                            toExplore.add(file.toPath());
                        } else {
                            Path p = this.resizedPicturesFolder.resolve(getResizedPictureFilename(file.toPath(), file.lastModified()));
                            toDeleteResizedPictures.remove(p);
                        }
                    }
                }
            }
        }

        // ResizedPictures with no real picture anymore
        for (Path toDeleteResizedPicture : toDeleteResizedPictures) {
            toDeleteResizedPicture.toFile().delete();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 13
Project: Panako   File: Application.java   View Source Code Vote up 5 votes
/**
 * Checks if a file exists and can be read.
 * @param file The file to check.
 * @return True if the file exists and can be read. False otherwise.
 */
private boolean checkFile(String file){
	File f = new File(file);
	boolean fileOk = false;
	if(f.exists() && f.canRead()){
		fileOk = true;
	}else{
		String message = "Could not read " + f.getAbsolutePath() + " it does not exist or is not accesible at the moment.)";
		LOG.warning(message);
		System.out.println(message);
	}
	return fileOk;
}
 
Example 14
Project: lams   File: ExportToolContentService.java   View Source Code Vote up 5 votes
/**
    * Import the learning design from the given path. Set the importer as the creator. If the workspaceFolderUid is
    * null then saves the design in the user's own workspace folder.
    *
    * @param designFile
    * @param importer
    * @param workspaceFolderUid
    * @return An object array where:
    *         <ul>
    *         <li>Object[0] = ldID (Long)</li>
    *         <li>Object[1] = ldErrors when importing (List<String>)</li>
    *         <li>Object[2] = toolErrors when importing (List<String>)</li>
    *         </ul>
    *
    * @throws ImportToolContentException
    */
   @Override
   public Object[] importLearningDesign(File designFile, User importer, Integer workspaceFolderUid,
    List<String> toolsErrorMsgs, String customCSV) throws ImportToolContentException {

Object[] ldResults = new Object[3];
Long ldId = null;
List<String> ldErrorMsgs = new ArrayList<String>();
String filename = designFile.getName();
String extension = (filename != null) && (filename.length() >= 4) ? filename.substring(filename.length() - 4)
	: "";

try {
    if (extension.equalsIgnoreCase(".zip")) {
	String ldPath = ZipFileUtil.expandZip(new FileInputStream(designFile), filename);

	File fullFilePath = new File(
		FileUtil.getFullPath(ldPath, ExportToolContentService.LEARNING_DESIGN_FILE_NAME));
	if (fullFilePath.canRead()) {
	    ldId = importLearningDesign(ldPath, importer, workspaceFolderUid, toolsErrorMsgs, customCSV);
	} else {
	    badFileType(ldErrorMsgs, filename, "Learning design file not found.");
	}
    } else {
	badFileType(ldErrorMsgs, filename, "Unexpected extension");
    }

} catch (Exception e) {
    throw new ImportToolContentException("Error while importing a sequence", e);
}

ldResults[0] = ldId;
ldResults[1] = ldErrorMsgs;
ldResults[2] = toolsErrorMsgs;
return ldResults;
   }
 
Example 15
Project: tablasco   File: FileSystemExpectedResultsLoader.java   View Source Code Vote up 5 votes
@Override
public InputStream load(final File expectedFile) throws FileNotFoundException
{
    if (!expectedFile.canRead())
    {
        throw new IllegalStateException("Could not find expected results '" + expectedFile
                + "' - if this is a new test, do you need to run this test in rebase mode first? (-Drebase=true)");
    }
    return new FileInputStream(expectedFile);
}
 
Example 16
Project: parabuild-ci   File: MyTreeNode.java   View Source Code Vote up 5 votes
public void explore() {
    File file = getFile();
  
    if (!isDirectory()) {
        return;
    }

    //Check if the file exists
    if (!file.exists()) {
        errorDisplayingNoDisk();
        return;
    }
    
    // Check if the file is readable.
    if (!file.canRead()) {
        errorDisplayingPermission();
        return;
    }
    
    if (!isExplored()) {
        File[] children = file.listFiles();

        if (children != null) {
            for (int i = 0; i < children.length; ++i) {
                if (children[i].isDirectory()) {
                    add(new MyTreeNode(children[i]));
                }
            }
        }

        explored = true;
    }
}
 
Example 17
Project: openddr-java   File: TestDataFileEntries.java   View Source Code Vote up 5 votes
private final File getDataFile() throws IOException {
    final String filename = System.getProperty(TEST_FILE_PROP);
    assertNotNull("Expecting non-null system property " + TEST_FILE_PROP, filename);
    final File f = new File(filename);
    if(!f.canRead()) {
        throw new IOException("File not found:" 
                + f.getAbsolutePath() 
                + " (defined by system property " + TEST_FILE_PROP + ")");
    }
    return f;
}
 
Example 18
Project: Recognize-it   File: MediaReader.java   View Source Code Vote up 4 votes
/**
 * Scan for image files.
 */
@WorkerThread
private void scanImageFile(Map<String, AlbumFolder> albumFolderMap, AlbumFolder allFileFolder) {
    ContentResolver contentResolver = mContext.getContentResolver();
    Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            IMAGES,
            null,
            null,
            MediaStore.Images.Media.DATE_ADDED);

    if (cursor != null) {
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor.getColumnIndex(IMAGES[0]));

            File file = new File(path);
            if (!file.exists() || !file.canRead()) continue;

            String name = cursor.getString(cursor.getColumnIndex(IMAGES[1]));
            String title = cursor.getString(cursor.getColumnIndex(IMAGES[2]));
            int bucketId = cursor.getInt(cursor.getColumnIndex(IMAGES[3]));
            String bucketName = cursor.getString(cursor.getColumnIndex(IMAGES[4]));
            String mimeType = cursor.getString(cursor.getColumnIndex(IMAGES[5]));
            long addDate = cursor.getLong(cursor.getColumnIndex(IMAGES[6]));
            long modifyDate = cursor.getLong(cursor.getColumnIndex(IMAGES[7]));
            float latitude = cursor.getFloat(cursor.getColumnIndex(IMAGES[8]));
            float longitude = cursor.getFloat(cursor.getColumnIndex(IMAGES[9]));
            long size = cursor.getLong(cursor.getColumnIndex(IMAGES[10]));

            AlbumFile imageFile = new AlbumFile();
            imageFile.setMediaType(AlbumFile.TYPE_IMAGE);
            imageFile.setPath(path);
            imageFile.setName(name);
            imageFile.setTitle(title);
            imageFile.setBucketId(bucketId);
            imageFile.setBucketName(bucketName);
            imageFile.setMimeType(mimeType);
            imageFile.setAddDate(addDate);
            imageFile.setModifyDate(modifyDate);
            imageFile.setLatitude(latitude);
            imageFile.setLongitude(longitude);
            imageFile.setSize(size);

            // Filter.
            if (mSizeFilter != null && mSizeFilter.filter(size)) {
                if (!mFilterVisibility) continue;
                imageFile.setEnable(false);
            }
            if (mMimeFilter != null && mMimeFilter.filter(mimeType)) {
                if (!mFilterVisibility) continue;
                imageFile.setEnable(false);
            }

            allFileFolder.addAlbumFile(imageFile);
            AlbumFolder albumFolder = albumFolderMap.get(bucketName);

            if (albumFolder != null)
                albumFolder.addAlbumFile(imageFile);
            else {
                albumFolder = new AlbumFolder();
                albumFolder.setId(bucketId);
                albumFolder.setName(bucketName);
                albumFolder.addAlbumFile(imageFile);

                albumFolderMap.put(bucketName, albumFolder);
            }
        }
        cursor.close();
    }
}
 
Example 19
Project: springreplugin   File: FileUtils.java   View Source Code Vote up 3 votes
/**
 * Opens a {@link FileInputStream} for the specified file, providing better
 * error messages than simply calling <code>new FileInputStream(file)</code>.
 * <p>
 * At the end of the method either the stream will be successfully opened,
 * or an exception will have been thrown.
 * <p>
 * An exception is thrown if the file does not exist.
 * An exception is thrown if the file object exists but is a directory.
 * An exception is thrown if the file exists but cannot be read.
 *
 * @param file the file to open for input, must not be {@code null}
 * @return a new {@link FileInputStream} for the specified file
 * @throws FileNotFoundException if the file does not exist
 * @throws IOException           if the file object is a directory
 * @throws IOException           if the file cannot be read
 */
public static FileInputStream openInputStream(final File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (file.canRead() == false) {
            throw new IOException("File '" + file + "' cannot be read");
        }
    } else {
        throw new FileNotFoundException("File '" + file + "' does not exist");
    }
    return new FileInputStream(file);
}
 
Example 20
Project: XinFramework   File: FileUtils.java   View Source Code Vote up 3 votes
/**
 * Opens a {@link FileInputStream} for the specified file, providing better
 * error messages than simply calling <code>new FileInputStream(file)</code>.
 * <p/>
 * At the end of the method either the stream will be successfully opened,
 * or an exception will have been thrown.
 * <p/>
 * An exception is thrown if the file does not exist.
 * An exception is thrown if the file object exists but is a directory.
 * An exception is thrown if the file exists but cannot be read.
 *
 * @param file the file to open for input, must not be {@code null}
 * @return a new {@link FileInputStream} for the specified file
 * @throws FileNotFoundException if the file does not exist
 * @throws IOException           if the file object is a directory
 * @throws IOException           if the file cannot be read
 * @since 1.3
 */
public static FileInputStream openInputStream(File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (!file.canRead()) {
            throw new IOException("File '" + file + "' cannot be read");
        }
    } else {
        throw new FileNotFoundException("File '" + file + "' does not exist");
    }
    return new FileInputStream(file);
}