java.io.File.getCanonicalFile()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(228)

本文整理了Java中java.io.File.getCanonicalFile()方法的一些代码示例,展示了File.getCanonicalFile()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.getCanonicalFile()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:getCanonicalFile

File.getCanonicalFile介绍

[英]Returns a new file created using the canonical path of this file. Equivalent to new File(this.getCanonicalPath()).
[中]返回使用此文件的规范路径创建的新文件。等效于新文件(this.getCanonicalPath())。

代码示例

代码示例来源:origin: gocd/gocd

public static boolean isSubdirectoryOf(File parent, File subdirectory) throws IOException {
  File parentFile = parent.getCanonicalFile();
  File current = subdirectory.getCanonicalFile();
  while (current != null) {
    if (current.equals(parentFile)) {
      return true;
    }
    current = current.getParentFile();
  }
  return false;
}

代码示例来源:origin: skylot/jadx

public static boolean isValidZipEntryName(String entryName) {
  try {
    File currentPath = new File(".").getCanonicalFile();
    File canonical = new File(currentPath, entryName).getCanonicalFile();
    if (isInSubDirectoryInternal(currentPath, canonical)) {
      return true;
    }
    LOG.error("Path traversal attack detected, invalid name: {}", entryName);
    return false;
  } catch (Exception e) {
    LOG.error("Path traversal attack detected, invalid name: {}", entryName);
    return false;
  }
}

代码示例来源:origin: neo4j/neo4j

private static String canonicalize( String path )
{
  try
  {
    return new File( path ).getCanonicalFile().getAbsolutePath();
  }
  catch ( IOException e )
  {
    return new File( path ).getAbsolutePath();
  }
}

代码示例来源:origin: android-hacker/VirtualXposed

public static boolean isSymlink(File file) throws IOException {
  if (file == null)
    throw new NullPointerException("File must not be null");
  File canon;
  if (file.getParent() == null) {
    canon = file;
  } else {
    File canonDir = file.getParentFile().getCanonicalFile();
    canon = new File(canonDir, file.getName());
  }
  return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

代码示例来源:origin: redisson/redisson

public URL find(String classname) {
  char sep = File.separatorChar;
  String filename = directory + sep
    + classname.replace('.', sep) + ".class";
  File f = new File(filename);
  if (f.exists())
    try {
      return f.getCanonicalFile().toURI().toURL();
    }
    catch (MalformedURLException e) {}
    catch (IOException e) {}
  return null;
}

代码示例来源:origin: sonyxperiadev/ApkAnalyser

public static File getRelativeFile(File baseFile, File fileToRelativize) throws IOException {
  if (baseFile.isFile()) {
    baseFile = baseFile.getParentFile();
  }
  return new File(getRelativeFileInternal(baseFile.getCanonicalFile(), fileToRelativize.getCanonicalFile()));
}

代码示例来源:origin: stackoverflow.com

String pid = new File("/proc/self").getCanonicalFile().getName();

代码示例来源:origin: commons-io/commons-io

final boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
  return false;
if (file1.isDirectory() || file2.isDirectory()) {
if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {

代码示例来源:origin: jMonkeyEngine/jmonkeyengine

public void setRootPath(String rootPath) {
  if (rootPath == null)
    throw new NullPointerException();
  
  try {
    root = new File(rootPath).getCanonicalFile();
    if (!root.isDirectory()){
      throw new IllegalArgumentException("Given root path \"" + root + "\" is not a directory");
    }
  } catch (IOException ex) {
    throw new AssetLoadException("Root path is invalid", ex);
  }
}

代码示例来源:origin: neo4j/neo4j

/**
 * Canonical file resolution on windows does not resolve links.
 * Real paths on windows can be resolved only using {@link Path#toRealPath(LinkOption...)}, but file should exist in that case.
 * We will try to do as much as possible and will try to use {@link Path#toRealPath(LinkOption...)} when file exist and will fallback to only
 * use {@link File#getCanonicalFile()} if file does not exist.
 * see JDK-8003887 for details
 * @param file - file to resolve canonical representation
 * @return canonical file representation.
 */
public static File getCanonicalFile( File file )
{
  try
  {
    File fileToResolve = file.exists() ? file.toPath().toRealPath().toFile() : file;
    return fileToResolve.getCanonicalFile();
  }
  catch ( IOException e )
  {
    throw new UncheckedIOException( e );
  }
}

代码示例来源:origin: google/guava

String name = f.getName();
if (f.isDirectory()) {
 File deref = f.getCanonicalFile();
 if (currentPath.add(deref)) {
  scanDirectory(deref, classloader, packagePrefix + name + "/", currentPath);

代码示例来源:origin: google/guava

/**
 * Creates any necessary but nonexistent parent directories of the specified file. Note that if
 * this operation fails it may have succeeded in creating some (but not all) of the necessary
 * parent directories.
 *
 * @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
 *     directories of the specified file could not be created.
 * @since 4.0
 */
public static void createParentDirs(File file) throws IOException {
 checkNotNull(file);
 File parent = file.getCanonicalFile().getParentFile();
 if (parent == null) {
  /*
   * The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
   * mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
   * -- or even that the caller can create it, but this method makes no such guarantees even for
   * non-root files.
   */
  return;
 }
 parent.mkdirs();
 if (!parent.isDirectory()) {
  throw new IOException("Unable to create parent directories of " + file);
 }
}

代码示例来源:origin: square/spoon

/** Get a relative URI for {@code file} from {@code output} folder. */
static String createRelativeUri(File file, File output) {
 if (file == null) {
  return null;
 }
 try {
  file = file.getCanonicalFile();
  output = output.getCanonicalFile();
  if (file.equals(output)) {
   throw new IllegalArgumentException("File path and output folder are the same.");
  }
  StringBuilder builder = new StringBuilder();
  while (!file.equals(output)) {
   if (builder.length() > 0) {
    builder.insert(0, "/");
   }
   builder.insert(0, file.getName());
   file = file.getParentFile().getCanonicalFile();
  }
  return builder.toString();
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: stackoverflow.com

public static boolean isSymlink(File file) throws IOException {
 if (file == null)
  throw new NullPointerException("File must not be null");
 File canon;
 if (file.getParent() == null) {
  canon = file;
 } else {
  File canonDir = file.getParentFile().getCanonicalFile();
  canon = new File(canonDir, file.getName());
 }
 return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

代码示例来源:origin: mpetazzoni/ttorrent

private File doCreateTempDir(String prefix, String suffix) throws IOException {
 prefix = prefix == null ? "" : prefix;
 suffix = suffix == null ? ".tmp" : suffix;
 do {
  int count = ourRandom.nextInt();
  final File f = new File(myCurrentTempDir, prefix + count + suffix);
  if (!f.exists() && f.mkdirs()) {
   return f.getCanonicalFile();
  }
 } while (true);
}

代码示例来源:origin: jeremylong/DependencyCheck

File f = new File(basePath);
try {
  f = f.getCanonicalFile();
  if (wildCards != null) {
    f = new File(f, wildCards);
  LOGGER.debug("Invalid path provided", ex);
return f.getAbsolutePath().replace('\\', '/');

代码示例来源:origin: sonyxperiadev/ApkAnalyser

public static String getRelativePath(String basePath, String pathToRelativize) throws IOException {
  File baseFile = new File(basePath);
  if (baseFile.isFile()) {
    baseFile = baseFile.getParentFile();
  }
  return getRelativeFileInternal(baseFile.getCanonicalFile(),
      new File(pathToRelativize).getCanonicalFile());
}

代码示例来源:origin: redisson/redisson

JarClassPath(String pathname) throws NotFoundException {
  try {
    jarfile = new JarFile(pathname);
    jarfileURL = new File(pathname).getCanonicalFile()
                    .toURI().toURL().toString();
    return;
  }
  catch (IOException e) {}
  throw new NotFoundException(pathname);
}

代码示例来源:origin: org.apache.logging.log4j/log4j-api

public static String getProcessId() {
    try {
      // LOG4J2-2126 use reflection to improve compatibility with Android Platform which does not support JMX extensions
      Class<?> managementFactoryClass = Class.forName("java.lang.management.ManagementFactory");
      Method getRuntimeMXBean = managementFactoryClass.getDeclaredMethod("getRuntimeMXBean");
      Class<?> runtimeMXBeanClass = Class.forName("java.lang.management.RuntimeMXBean");
      Method getName = runtimeMXBeanClass.getDeclaredMethod("getName");

      Object runtimeMXBean = getRuntimeMXBean.invoke(null);
      String name = (String) getName.invoke(runtimeMXBean);
      //String name = ManagementFactory.getRuntimeMXBean().getName(); //JMX not allowed on Android
      return name.split("@")[0]; // likely works on most platforms
    } catch (final Exception ex) {
      try {
        return new File("/proc/self").getCanonicalFile().getName(); // try a Linux-specific way
      } catch (final IOException ignoredUseDefault) {
        // Ignore exception.
      }
    }
    return DEFAULT_PROCESSID;
  }
}

代码示例来源:origin: commons-io/commons-io

final boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
  return false;
if (file1.isDirectory() || file2.isDirectory()) {
if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {

相关文章