本文整理汇总了Java中java.io.File.canRead方法的典型用法代码示例。如果您正苦于以下问题:Java File.canRead方法的具体用法?Java File.canRead怎么用?Java File.canRead使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.io.File
的用法示例。
在下文中一共展示了File.canRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: buildScript
import java.io.File; //导入方法依赖的package包/类
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);
}
示例2: getFileStatus
import java.io.File; //导入方法依赖的package包/类
/**
* 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;
}
示例3: getSize
import java.io.File; //导入方法依赖的package包/类
/**
* 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;
}
示例4: checkAclFile
import java.io.File; //导入方法依赖的package包/类
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);
}
}
示例5: getInstance
import java.io.File; //导入方法依赖的package包/类
/**
* 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;
}
示例6: retrieveRelevantFiles
import java.io.File; //导入方法依赖的package包/类
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);
}
示例7: onCreate
import java.io.File; //导入方法依赖的package包/类
@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;
};
}
示例8: getTrustedSslContext
import java.io.File; //导入方法依赖的package包/类
/**
* 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);
}
}
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:46,代码来源:FileTrustStoreSslSocketFactory.java
示例9: main
import java.io.File; //导入方法依赖的package包/类
/**
* 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();
}
示例10: _showDirectoryContents
import java.io.File; //导入方法依赖的package包/类
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;
}
}
示例11: defineFinderClass
import java.io.File; //导入方法依赖的package包/类
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"));
}
}
}
示例12: initAndCleanOutdatedResizedPictures
import java.io.File; //导入方法依赖的package包/类
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();
}
}
示例13: checkFile
import java.io.File; //导入方法依赖的package包/类
/**
* 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;
}
示例14: importLearningDesign
import java.io.File; //导入方法依赖的package包/类
/**
* 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;
}
示例15: load
import java.io.File; //导入方法依赖的package包/类
@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);
}