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

The following examples show how to use java.io.File#canRead() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java    From WorldPainter with GNU General Public License v3.0 6 votes vote down vote up
private static void configError(Throwable e) {
    // Try to preserve the config file
    File configFile = Configuration.getConfigFile();
    if (configFile.isFile() && configFile.canRead()) {
        File backupConfigFile = new File(configFile.getParentFile(), configFile.getName() + ".old");
        try {
            FileUtils.copyFileToFile(configFile, backupConfigFile, true);
        } catch (IOException e1) {
            logger.error("I/O error while trying to preserve faulty config file", e1);
        }
    }

    // Report the error
    logger.error("Exception while initialising configuration", e);
    JOptionPane.showMessageDialog(null, "Could not read configuration file! Resetting configuration.\n\nException type: " + e.getClass().getSimpleName() + "\nMessage: " + e.getMessage(), "Configuration Error", JOptionPane.ERROR_MESSAGE);
}
 
Example 2
Source File: ProjectLayout.java    From actframework with Apache License 2.0 6 votes vote down vote up
/**
 * check if a dir is application base as per given project layout
 *
 * @param dir    the folder to be probed
 * @param layout the project layout used to probe the folder
 * @return {@code true if the folder is app base as per given project layout}
 */
public static boolean probeAppBase(File dir, ProjectLayout layout) {
    // try conf file
    File conf = layout.conf(dir);
    if (null != conf && conf.canRead() && conf.isFile()) {
        return true;
    }
    // try source path
    File src = layout.source(dir);
    if (null != src && src.canRead() && src.isDirectory()) {
        // try target path
        File tgt = layout.target(dir);
        return (null != tgt && tgt.canRead() && tgt.isDirectory());
    }
    return false;
}
 
Example 3
Source File: Helpers.java    From UnityOBBDownloader with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: ConfigUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
public static File[] getTestDependencies() {
    File libDir = new File(IGlobalOptions.CONF_DIR, "lib");
    if(libDir.exists() && libDir.canRead() && libDir.isDirectory()) {
        return libDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.getName().toLowerCase().endsWith(".jar")
                        && pathname.canRead()
                        && pathname.isFile()) {
                    return true;
                }
                return false;
            }
        });
    }
    else {
        return new File[]{};
    }
}
 
Example 5
Source File: TestUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Returns current jdk directory
    */    
   public static File getJdkDir() {

Properties p = System.getProperties();	
String javaHomeProp = p.getProperty( "java.home" );

if ( javaHomeProp == null ) {
    throw new IllegalStateException( "Can't find java.home property ");
}
else {
    File jre = new File( javaHomeProp );
    if ( !jre.canRead() ) {
	throw new IllegalStateException( "Can't read " + jre );
    }
    File dir = jre.getParentFile();
    if ( !jre.canRead() ) {
	throw new IllegalStateException( "Can't read " + dir);
    }
    return dir;
}
   }
 
Example 6
Source File: TestSources.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static String accessTestData(String testprefix, String basename, TestPart part) throws Exception {

    String fname = testprefix + File.separator + basename + partext(part);

    String result = null;
    try {
      File f = new File(fname);
      if (!f.canRead())
        return null;
      FileReader fr = new FileReader(fname);
      StringBuffer cbuf = new StringBuffer();
      int c;
      while ((c = fr.read()) != -1) {
        cbuf.append((char) c);
      }
      return cbuf.toString();
    } catch (Exception e) {
      System.err.println("File io failure: " + e.toString());
      e.printStackTrace();
      throw e;
    }

  }
 
Example 7
Source File: MultiRelease.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
File mkdir(File f) throws IOException {
    if (f.exists() && f.isDirectory() && f.canRead() && f.canWrite()) {
        return f;
    }
    if (!f.mkdirs()) {
       throw new IOException("mkdirs failed: " + f.getAbsolutePath());
    }
    return f;
}
 
Example 8
Source File: FileUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Validate a file path and return {@code null} if it is valid, otherwise an error.
 * <p>
 * A valid file means that the <tt>filePath</tt> represents a valid, readable file
 * with absolute file path.
 * @param source source used in error message (e.g. "Script", "Config file")
 * @param filePath a file path to validate
 * @param writable {@code true} if the file must be writable, {@code false} otherwise
 * @return {@code null} if it is valid, otherwise an error
 */
@NbBundle.Messages({
    "# {0} - source",
    "FileUtils.validateFile.missing={0} must be selected.",
    "# {0} - source",
    "FileUtils.validateFile.notAbsolute={0} must be an absolute path.",
    "# {0} - source",
    "FileUtils.validateFile.notFile={0} must be a valid file.",
    "# {0} - source",
    "FileUtils.validateFile.notReadable={0} is not readable.",
    "# {0} - source",
    "FileUtils.validateFile.notWritable={0} is not writable."
})
@CheckForNull
public static String validateFile(String source, String filePath, boolean writable) {
    if (!StringUtils.hasText(filePath)) {
        return Bundle.FileUtils_validateFile_missing(source);
    }

    File file = new File(filePath);
    if (!file.isAbsolute()) {
        return Bundle.FileUtils_validateFile_notAbsolute(source);
    } else if (!file.isFile()) {
        return Bundle.FileUtils_validateFile_notFile(source);
    } else if (!file.canRead()) {
        return Bundle.FileUtils_validateFile_notReadable(source);
    } else if (writable && !file.canWrite()) {
        return Bundle.FileUtils_validateFile_notWritable(source);
    }
    return null;
}
 
Example 9
Source File: HotSpotMXBeanStatistics.java    From garmadon with Apache License 2.0 5 votes vote down vote up
/**
 * @return current Linux FS cache buffers size. It reduces the free space so you may add it to free space to get actual free space.
 */
static long getLinuxFSCacheSize() {
    File meminfo = new File("/proc/meminfo");
    if (!meminfo.exists() || !meminfo.canRead()) return 0;
    try {
        try (BufferedReader reader = new BufferedReader(new FileReader(meminfo))) {
            return parseLinuxFSCacheSize(reader);
        }
    } catch (IOException ex) {
        return 0;
    }
}
 
Example 10
Source File: ExternalGroups.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
public static ExternalGroups fromConfiguration() throws IOException {
  checkState(Configuration.isInitialized(), "configuration must be initialized");
  String groupsFilename = Configuration.getString(CONFIG_EXTERNALGROUPS_FILENAME, null).get();
  logger.log(Level.CONFIG, CONFIG_EXTERNALGROUPS_FILENAME + ": " + groupsFilename);
  File groupsFile = new File(groupsFilename);
  if (!(groupsFile.exists() && groupsFile.canRead())) {
    throw new InvalidConfigurationException(groupsFilename + " can't be read");
  }
  return fromFile(groupsFile);
}
 
Example 11
Source File: SecurityConfiguration.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void validate() {
	if (!StringUtils.isBlank(keytab)) {
		// principal is required
		if (StringUtils.isBlank(principal)) {
			throw new IllegalConfigurationException("Kerberos login configuration is invalid; keytab requires a principal.");
		}

		// check the keytab is readable
		File keytabFile = new File(keytab);
		if (!keytabFile.exists() || !keytabFile.isFile() || !keytabFile.canRead()) {
			throw new IllegalConfigurationException("Kerberos login configuration is invalid; keytab is unreadable");
		}
	}
}
 
Example 12
Source File: SVGImageElement.java    From latexdraw with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean enableRendering() {
	if(getWidth() == 0d || getHeight() == 0d) {
		return false;
	}

	try {
		final URI uri = new URI(getURI());
		final File f = new File(uri.getPath());
		return f.exists() && f.canRead();
	}catch(final URISyntaxException ex) {
		return false;
	}
}
 
Example 13
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an instance.
 *
 * @param definingContext the context in which any as-yet unresolved
 * classes should be defined
 * @param dexPath list of dex/resource path elements, separated by
 * {@code File.pathSeparator}
 * @param libraryPath list of native library directory path elements,
 * separated by {@code File.pathSeparator}
 * @param optimizedDirectory directory where optimized {@code .dex} files
 * should be found and written to, or {@code null} to use the default
 * system directory for same
 */
public DexPathList(ClassLoader definingContext, String dexPath,
        String libraryPath, File optimizedDirectory) {
    if (definingContext == null) {
        throw new NullPointerException("definingContext == null");
    }

    if (dexPath == null) {
        throw new NullPointerException("dexPath == null");
    }

    if (optimizedDirectory != null) {
        if (!optimizedDirectory.exists())  {
            throw new IllegalArgumentException(
                    "optimizedDirectory doesn't exist: "
                    + optimizedDirectory);
        }

        if (!(optimizedDirectory.canRead()
                        && optimizedDirectory.canWrite())) {
            throw new IllegalArgumentException(
                    "optimizedDirectory not readable/writable: "
                    + optimizedDirectory);
        }
    }

    this.definingContext = definingContext;
    ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
    this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory,
                                       suppressedExceptions);
    if (suppressedExceptions.size() > 0) {
        this.dexElementsSuppressedExceptions =
            suppressedExceptions.toArray(new IOException[suppressedExceptions.size()]);
    } else {
        dexElementsSuppressedExceptions = null;
    }
    this.nativeLibraryDirectories = splitLibraryPath(libraryPath);
}
 
Example 14
Source File: AppBuilder.java    From actframework with Apache License 2.0 5 votes vote down vote up
void copyResources() {
    File resource = layout.resource(appBase);
    if (null == resource || !resource.canRead()) {
        return;
    }
    verifyDir(resource, "resource", false);
    IO.copyDirectory(resource, tgtClasses);
}
 
Example 15
Source File: Main.java    From revapi with Apache License 2.0 5 votes vote down vote up
private static void checkCanRead(File f, String errorMessagePrefix) throws IllegalArgumentException {
    if (!f.exists()) {
        throw new IllegalArgumentException(errorMessagePrefix + " '" + f.getAbsolutePath() + "' does not exist.");
    }

    if (!f.isFile() || !f.canRead()) {
        throw new IllegalArgumentException(
                errorMessagePrefix + " '" + f.getAbsolutePath() + "' is not a file or cannot be read.");
    }
}
 
Example 16
Source File: FileDialogPreference.java    From VIA-AI with MIT License 5 votes vote down vote up
private boolean isFileExist(String path)  {
    boolean ret = false;

    if(path.length() > 0) {
        File file = new File(path);
        if (file.exists() && file.canWrite() && file.canRead()) ret = true;
    }
    return ret;
}
 
Example 17
Source File: BinaryDictionaryGetter.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of file addresses for a given locale, trying relevant methods in order.
 *
 * Tries to get binary dictionaries from various sources, in order:
 * - Uses a content provider to get a public dictionary set, as per the protocol described
 *   in BinaryDictionaryFileDumper.
 * If that fails:
 * - Gets a file name from the built-in dictionary for this locale, if any.
 * If that fails:
 * - Returns null.
 * @return The list of addresses of valid dictionary files, or null.
 */
public static ArrayList<AssetFileAddress> getDictionaryFiles(final Locale locale,
        final Context context, boolean notifyDictionaryPackForUpdates) {
    if (notifyDictionaryPackForUpdates) {
        final boolean hasDefaultWordList = DictionaryInfoUtils.isDictionaryAvailable(
                context, locale);
        // It makes sure that the first time keyboard comes up and the dictionaries are reset,
        // the DB is populated with the appropriate values for each locale. Helps in downloading
        // the dictionaries when the user enables and switches new languages before the
        // DictionaryService runs.
        BinaryDictionaryFileDumper.downloadDictIfNeverRequested(
                locale, context, hasDefaultWordList);

        // Move a staging files to the cache ddirectories if any.
        DictionaryInfoUtils.moveStagingFilesIfExists(context);
    }
    final File[] cachedWordLists = getCachedWordLists(locale.toString(), context);
    final String mainDictId = DictionaryInfoUtils.getMainDictId(locale);
    final DictPackSettings dictPackSettings = new DictPackSettings(context);

    boolean foundMainDict = false;
    final ArrayList<AssetFileAddress> fileList = new ArrayList<>();
    // cachedWordLists may not be null, see doc for getCachedDictionaryList
    for (final File f : cachedWordLists) {
        final String wordListId = DictionaryInfoUtils.getWordListIdFromFileName(f.getName());
        final boolean canUse = f.canRead() && hackCanUseDictionaryFile(f);
        if (canUse && DictionaryInfoUtils.isMainWordListId(wordListId)) {
            foundMainDict = true;
        }
        if (!dictPackSettings.isWordListActive(wordListId)) continue;
        if (canUse) {
            final AssetFileAddress afa = AssetFileAddress.makeFromFileName(f.getPath());
            if (null != afa) fileList.add(afa);
        } else {
            Log.e(TAG, "Found a cached dictionary file for " + locale.toString()
                    + " but cannot read or use it");
        }
    }

    if (!foundMainDict && dictPackSettings.isWordListActive(mainDictId)) {
        final int fallbackResId =
                DictionaryInfoUtils.getMainDictionaryResourceId(context.getResources(), locale);
        final AssetFileAddress fallbackAsset = loadFallbackResource(context, fallbackResId);
        if (null != fallbackAsset) {
            fileList.add(fallbackAsset);
        }
    }

    return fileList;
}
 
Example 18
Source File: ConfigFileRegistryAuthSupplier.java    From docker-client with Apache License 2.0 4 votes vote down vote up
private boolean configFileExists() {
  final File f = this.path.toFile();
  return f.isFile() && f.canRead();
}
 
Example 19
Source File: LogFileLoaderProvider.java    From jd-gui with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean accept(API api, File file) {
    return file.exists() && file.isFile() && file.canRead() && file.getName().toLowerCase().endsWith(".log");
}
 
Example 20
Source File: JpaSchemaGeneratorMojo.java    From jpa-schema-maven-plugin with Apache License 2.0 4 votes vote down vote up
private ClassLoader getProjectClassLoader() throws MojoExecutionException {
    try {
        // compiled classes
        List<String> classfiles = this.project.getCompileClasspathElements();
        if (this.scanTestClasses) {
            classfiles.addAll(this.project.getTestClasspathElements());
        }
        // classpath to url
        List<URL> classURLs = new ArrayList<>(classfiles.size());
        for (String classfile : classfiles) {
            classURLs.add(new File(classfile).toURI().toURL());
        }

        // dependency artifacts to url
        ArtifactResolutionRequest sharedreq = new ArtifactResolutionRequest().setResolveRoot(true)
                                                                             .setResolveTransitively(true)
                                                                             .setLocalRepository(this.session.getLocalRepository())
                                                                             .setRemoteRepositories(this.project.getRemoteArtifactRepositories());

        ArtifactRepository repository = this.session.getLocalRepository();
        Set<Artifact> artifacts = this.project.getDependencyArtifacts();
        for (Artifact artifact : artifacts) {
            if (!Artifact.SCOPE_TEST.equalsIgnoreCase(artifact.getScope())) {
                ArtifactResolutionRequest request = new ArtifactResolutionRequest(sharedreq).setArtifact(artifact);
                ArtifactResolutionResult result = this.repositorySystem.resolve(request);
                if (result.isSuccess()) {
                    File file = repository.find(artifact).getFile();
                    if (file != null && file.isFile() && file.canRead()) {
                        classURLs.add(file.toURI().toURL());
                    }
                }
            }
        }

        for (URL url : classURLs) {
            this.log.info("  * classpath: " + url);
        }

        return new URLClassLoader(classURLs.toArray(EMPTY_URLS), this.getClass().getClassLoader());
    } catch (Exception e) {
        this.log.error(e);
        throw new MojoExecutionException("Error while creating classloader", e);
    }
}