下面列出了java.io.File#getCanonicalFile ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag);
if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri);
}
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
private boolean isSymlink(final File file) throws IOException {
File canon = null;
String _parent = file.getParent();
boolean _equals = Objects.equal(_parent, null);
if (_equals) {
canon = file;
} else {
File _parentFile = file.getParentFile();
File canonDir = _parentFile.getCanonicalFile();
String _name = file.getName();
File _file = new File(canonDir, _name);
canon = _file;
}
File _canonicalFile = canon.getCanonicalFile();
File _absoluteFile = canon.getAbsoluteFile();
boolean _equals_1 = _canonicalFile.equals(_absoluteFile);
return (!_equals_1);
}
/**
* Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots.
*/
public void addRoot(String name, File root) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
try {
// Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e);
}
mRoots.put(name, root);
}
private static Set<File> getCanonicalFiles(String[] paths) {
Set<File> files = new HashSet<>(paths.length);
for (String root : paths) {
File rootFile = new File(root);
try {
rootFile = rootFile.getCanonicalFile();
} catch (IOException ioex) {}
files.add(rootFile);
}
return Collections.unmodifiableSet(files);
}
@Override
public String getSourceLocation() {
File file = new File(fArchivePath);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
// Will still work but might have extra ../ in the path
}
URI uri = file.toURI();
IPath entryPath = new Path(fFileSystemObject.getName());
URI jarURI = entryPath.isRoot() ? URIUtil.toJarURI(uri, Path.EMPTY) : URIUtil.toJarURI(uri, entryPath);
return URIUtil.toUnencodedString(jarURI);
}
private static File resolveTmpDir() {
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
try {
return tmpDir.getCanonicalFile();
}
catch (IOException e) { // NOSONAR: fall back to 'best-effort' absolute form
return tmpDir.getAbsoluteFile();
}
}
public static File getCanonicalFile(File f) {
try {
return f.getCanonicalFile();
} catch (IOException e) {
return f.getAbsoluteFile();
}
}
/**
* Checks, whether the child directory is a subdirectory of the base directory.
*
* @param base the base directory.
* @param child the suspected child directory.
* @return true, if the child is a subdirectory of the base directory.
* @throws java.io.IOException if an IOError occured during the test.
*/
public boolean isSubDirectory( File base, File child )
throws IOException {
base = base.getCanonicalFile();
child = child.getCanonicalFile();
File parentFile = child;
while ( parentFile != null ) {
if ( base.equals( parentFile ) ) {
return true;
}
parentFile = parentFile.getParentFile();
}
return false;
}
@Override
public List<Info> list(SingleCloverURI parent, ListParameters params) throws IOException {
URI uri = parent.toURI();
File file = new File(uri);
try {
file = file.getCanonicalFile();
} catch (IOException ex) {
// ignore
}
if (!file.exists() || (uri.toString().endsWith(URIUtils.PATH_SEPARATOR) && !file.isDirectory())) {
throw new FileNotFoundException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.not_a_directory"), file)); //$NON-NLS-1$
}
return list(file.toPath(), params);
}
public void run() {
//myLog.l(Log.DEBUG, "CWD executing");
String param = getParameter(input);
File newDir;
String errString = null;
mainblock: {
newDir = inputPathToChrootedFile(sessionThread.getWorkingDir(), param);
// Ensure the new path does not violate the chroot restriction
if(violatesChroot(newDir)) {
errString = "550 Invalid name or chroot violation\r\n";
sessionThread.writeString(errString);
//myLog.l(Log.INFO, errString);
break mainblock;
}
try {
newDir = newDir.getCanonicalFile();
if(!newDir.isDirectory()) {
sessionThread.writeString("550 Can't CWD to invalid directory\r\n");
} else if(newDir.canRead()) {
sessionThread.setWorkingDir(newDir);
sessionThread.writeString("250 CWD successful\r\n");
} else {
sessionThread.writeString("550 That path is inaccessible\r\n");
}
} catch(IOException e) {
sessionThread.writeString("550 Invalid path\r\n");
break mainblock;
}
}
//myLog.l(Log.DEBUG, "CWD complete");
}
/**
* Constructs a new instance backed by the given File object.
*
* @param file used to back this BLOB instance.
* @param deleteOnFree Assigns whether an attempt to delete the backing file
* is to be made in response to invocation of {@link #free()}.
* @throws SQLException If an I/O error occurs, which is possible because
* the construction of the canonical pathname may require file system
* queries; if a required system property value cannot be accessed,
* or if a security manager exists and its <code>{@link
* java.lang.SecurityManager#checkRead}</code> method denies
* read access to the file
*/
public JDBCBlobFile(final File file,
boolean deleteOnFree) throws SQLException {
m_deleteOnFree = deleteOnFree;
try {
m_file = file.getCanonicalFile();
} catch (Exception ex) {
throw JDBCUtil.sqlException(ex);
}
checkIsFile( /*checkExists*/false);
}
private static File canon(File file) {
try {
return file.getCanonicalFile();
} catch (IOException e) {
return file;
}
}
public ConsoleFile getFile(String path, boolean mustExist)
throws IOException {
File newFile = new File(path);
if (newFile.isAbsolute()) {
newFile = newFile.getCanonicalFile();
} else {
newFile = new File(file, path).getCanonicalFile();
}
if (!newFile.exists() && mustExist) {
throw new FileNotFoundException(newFile.getPath());
}
return new PlatformFile(newFile);
}
/**
* Convert a uri generated by a fileprovider, like content://AUTHORITY/ROOT/actual/path
* to a file pointing to file:///actual/path
*
* Note that it only works for paths generated with `ROOT` as the path element. This is done if
* nnf_provider_paths.xml is used to define the file provider in the manifest.
*
* @param uri generated from a file provider
* @return Corresponding {@link File} object
*/
@NonNull
public static File getFileForUri(@NonNull Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
if (!"root".equalsIgnoreCase(tag)) {
throw new IllegalArgumentException(
String.format("Can't decode paths to '%s', only for 'root' paths.",
tag));
}
final File root = new File("/");
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
public File getCanonicalFile(File file) {
try {
return file.getCanonicalFile();
} catch (IOException e) {
return file.getAbsoluteFile();
}
}
public void updateRecent(File file) {
File fileToSave = file;
try {
fileToSave = file.getCanonicalFile();
} catch (IOException e) {
}
long now = System.currentTimeMillis();
int index = getReplacementIndex(now, fileToSave);
updateInto(index, now, fileToSave);
}
/**
* Computes an "application hash", a reasonably unique identifier for an app.
* <p>
* This is currently used by Instant Run to prevent apps on a device from guessing
* the authentication token associated with an instant run developed app on the same
* device.
* <p>
* This method creates the "secret", the field in the AppInfo class which is used as a simple
* authentication token between the IDE and the app server.
* <p>
* This is not a cryptographically strong unique id; we could attempt to make a truly random
* number here, but we'd need to store that id somewhere such that subsequent builds
* will use the same secret, to avoid having the IDE and the app getting out of sync,
* and there isn't really a natural place for us to store the key to make it survive across
* a clean build. (One possibility is putting it into local.properties).
* <p>
* However, we have much simpler needs: we just need a key that can't be guessed from
* a hostile app on the developer's device, and it only has a few guesses (after providing
* the wrong secret to the server a few times, the server will shut down.) We can't
* rely on the package name along, since the port number is known, and the package name is
* discoverable by the hostile app (by querying the contents of /data/data/*). Therefore
* we also include facts that the hostile app can't know, such as as the path on the
* developer's machine to the app project and the name of the developer's machine, etc.
* The goal is for this secret to be reasonably stable (e.g. the same from build to build)
* yet not something an app could guess if it only has a couple of tries.
*/
public static long computeApplicationHash(@NonNull File projectDir) {
HashFunction hashFunction = Hashing.md5();
Hasher hasher = hashFunction.newHasher();
try {
projectDir = projectDir.getCanonicalFile();
} catch (IOException ignore) {
// If this throws an exception the assignment won't
// be done and we'll stick with the regular project dir
}
String path = projectDir.getPath();
hasher.putBytes(path.getBytes(Charsets.UTF_8));
String user = System.getProperty("user.name");
if (user != null) {
hasher.putBytes(user.getBytes(Charsets.UTF_8));
}
return hasher.hash().asLong();
}
public URL publishResource(File resource)
throws Exception {
synchronized (this) {
resource = resource.getCanonicalFile();
URL result = new URL("http://" + my_ip + ":" + my_port + "/"
+ resource_id_next++ + "/" + resource.getName());
published_resources.put(result.getPath(), resource);
if (logger != null) {
logger.log("Local resource added: " + resource + " -> " + result);
}
return (result);
}
}
/**
* Adds the directory to the model and sets it to be selected,
* additionally clears out the previous selected directory and
* the paths leading up to it, if any.
*/
private void addItem(File directory) {
if(directory == null) {
return;
}
boolean useShellFolder = FilePane.usesShellFolder(chooser);
directories.clear();
File[] baseFolders = (useShellFolder)
? (File[]) ShellFolder.get("fileChooserComboBoxFolders")
: fsv.getRoots();
directories.addAll(Arrays.asList(baseFolders));
// Get the canonical (full) path. This has the side
// benefit of removing extraneous chars from the path,
// for example /foo/bar/ becomes /foo/bar
File canonical;
try {
canonical = directory.getCanonicalFile();
} catch (IOException e) {
// Maybe drive is not ready. Can't abort here.
canonical = directory;
}
// create File instances of each directory leading up to the top
try {
File sf = useShellFolder ? ShellFolder.getShellFolder(canonical)
: canonical;
File f = sf;
Vector<File> path = new Vector<File>(10);
do {
path.addElement(f);
} while ((f = f.getParentFile()) != null);
int pathCount = path.size();
// Insert chain at appropriate place in vector
for (int i = 0; i < pathCount; i++) {
f = path.get(i);
if (directories.contains(f)) {
int topIndex = directories.indexOf(f);
for (int j = i-1; j >= 0; j--) {
directories.insertElementAt(path.get(j), topIndex+i-j);
}
break;
}
}
calculateDepths();
setSelectedItem(sf);
} catch (FileNotFoundException ex) {
calculateDepths();
}
}
public static synchronized void registerDirectory(File dir) {
// Note that this does not currently check to see whether the
// directory has previously been registered, since the meta-index
// in a particular directory creates multiple entries in the
// jarMap. If this mechanism is extended beyond the boot and
// extension class paths (for example, automatically searching for
// meta-index files in directories containing jars which have been
// explicitly opened) then this code should be generalized.
//
// This method must be called from a privileged context.
File indexFile = new File(dir, "meta-index");
if (indexFile.exists()) {
try {
BufferedReader reader = new BufferedReader(new FileReader(indexFile));
String line = null;
String curJarName = null;
boolean isCurJarContainClassOnly = false;
List<String> contents = new ArrayList<String>();
Map<File, MetaIndex> map = getJarMap();
/* Convert dir into canonical form. */
dir = dir.getCanonicalFile();
/* Note: The first line should contain the version of
* the meta-index file. We have to match the right version
* before trying to parse this file. */
line = reader.readLine();
if (line == null ||
!line.equals("% VERSION 2")) {
reader.close();
return;
}
while ((line = reader.readLine()) != null) {
switch (line.charAt(0)) {
case '!':
case '#':
case '@': {
// Store away current contents, if any
if ((curJarName != null) && (contents.size() > 0)) {
map.put(new File(dir, curJarName),
new MetaIndex(contents,
isCurJarContainClassOnly));
contents.clear();
}
// Fetch new current jar file name
curJarName = line.substring(2);
if (line.charAt(0) == '!') {
isCurJarContainClassOnly = true;
} else if (isCurJarContainClassOnly) {
isCurJarContainClassOnly = false;
}
break;
}
case '%':
break;
default: {
contents.add(line);
}
}
}
// Store away current contents, if any
if ((curJarName != null) && (contents.size() > 0)) {
map.put(new File(dir, curJarName),
new MetaIndex(contents, isCurJarContainClassOnly));
}
reader.close();
} catch (IOException e) {
// Silently fail for now (similar behavior to elsewhere in
// extension and core loaders)
}
}
}