下面列出了java.io.File#canRead ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
/** 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;
}
}
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;
}
}
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[]{};
}
}
/**
* 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;
}
/**
* 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;
}
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;
}
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;
}
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.");
}
}
void copyResources() {
File resource = layout.resource(appBase);
if (null == resource || !resource.canRead()) {
return;
}
verifyDir(resource, "resource", false);
IO.copyDirectory(resource, tgtClasses);
}
/**
* 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);
}
@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;
}
}
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");
}
}
}
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);
}
/**
* @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;
}
}
/**
* 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;
}
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);
}
}
@Override
public boolean accept(API api, File file) {
return file.exists() && file.isFile() && file.canRead() && file.getName().toLowerCase().endsWith(".log");
}
private boolean configFileExists() {
final File f = this.path.toFile();
return f.isFile() && f.canRead();
}
/**
* 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;
}