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

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

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

File.getCanonicalPath介绍

[英]Returns the canonical path of this file. An absolute path is one that begins at the root of the file system. A canonical path is an absolute path with symbolic links and references to "." or ".." resolved. If a path element does not exist (or is not searchable), there is a conflict between interpreting canonicalization as a textual operation (where "a/../b" is "b" even if "a" does not exist) .

Most callers should use #getAbsolutePath instead. A canonical path is significantly more expensive to compute, and not generally useful. The primary use for canonical paths is determining whether two paths point to the same file by comparing the canonicalized paths.

It can be actively harmful to use a canonical path, specifically because canonicalization removes symbolic links. It's wise to assume that a symbolic link is present for a reason, and that that reason is because the link may need to change. Canonicalization removes this layer of indirection. Good code should generally avoid caching canonical paths.
[中]返回此文件的规范路径。绝对路径是从文件系统的根开始的路径。规范路径是带有符号链接和对“”的引用的绝对路径或“.”断然的。如果路径元素不存在(或不可搜索),则将规范化解释为文本操作(其中“a/。/b”是“b”,即使“a”不存在),两者之间存在冲突。
大多数呼叫者应该使用#getAbsolutePath。标准路径的计算成本要高得多,而且通常不太有用。规范化路径的主要用途是通过比较规范化路径来确定两个路径是否指向同一个文件。
使用规范化路径可能非常有害,特别是因为规范化会删除符号链接。明智的做法是假设符号链接的存在是有原因的,而这个原因是因为链接可能需要更改。规范化消除了这一层的间接性。好的代码通常应该避免缓存规范路径。

代码示例

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

private boolean checkDirectoryValidity (String directory) {
  File checkFile = new File(directory);
  boolean path = true;
  // try to get the canonical path, if this fails the path is not valid
  try {
    checkFile.getCanonicalPath();
  } catch (Exception e) {
    path = false;
  }
  return path;
}

代码示例来源:origin: org.testng/testng

private static String toString(File path) {
   try {
   return path.getCanonicalPath();
   } catch(IOException e) {
   return path.getAbsolutePath();
   }
 }
}

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

public static String currentWorkingDirectory() {
  String location;
  File file = new File(".");
  try {
    location = file.getCanonicalPath();
  } catch (IOException e) {
    location = file.getAbsolutePath();
  }
  return location;
}

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

public static boolean isSymbolicLink(File parent, String name)
    throws IOException {
  if (parent == null) {
    File f = new File(name);
    parent = f.getParentFile();
    name = f.getName();
  }
  File toTest = new File(parent.getCanonicalPath(), name);
  return !toTest.getAbsolutePath().equals(toTest.getCanonicalPath());
}

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

System.out.println(new File(".").getCanonicalPath());

代码示例来源:origin: apache/storm

/**
 * Return a metadata file (worker.yaml) for given worker log directory.
 * @param logDir worker log directory
 */
public Optional<File> getMetadataFileForWorkerLogDir(File logDir) throws IOException {
  File metaFile = new File(logDir, WORKER_YAML);
  if (metaFile.exists()) {
    return Optional.of(metaFile);
  } else {
    LOG.warn("Could not find {} to clean up for {}", metaFile.getCanonicalPath(), logDir);
    return Optional.empty();
  }
}

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

public static void main(String[] args) throws IOException {
 // find the file in the file system.. probably not a good idea
 File f = new File("images/test.jpg");
 System.out.println(f.getCanonicalPath()+" "+f.exists());

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

import java.io.File;
public class PathTesting {
  public static void main(String [] args) {
    File f = new File("test/.././file.txt");
    System.out.println(f.getPath());
    System.out.println(f.getAbsolutePath());
    try {
      System.out.println(f.getCanonicalPath());
    }
    catch(Exception e) {}
  }
}

代码示例来源:origin: apache/geode

private void verifyLogFileContents(Set<String> acceptedLogLevels, File dirForMember)
  throws IOException {
 String memberName = dirForMember.getName();
 MemberVM member = expectedMessages.keySet().stream()
   .filter((Member aMember) -> aMember.getName().equals(memberName)).findFirst().get();
 assertThat(member).isNotNull();
 Set<String> fileNamesInDir =
   Stream.of(dirForMember.listFiles()).map(File::getName).collect(toSet());
 System.out.println(dirForMember.getCanonicalPath() + " : " + fileNamesInDir);
 File logFileForMember = new File(dirForMember, memberName + ".log");
 assertThat(logFileForMember).exists();
 String logFileContents = FileUtils.readLines(logFileForMember, Charset.defaultCharset())
   .stream().collect(joining("\n"));
 for (LogLine logLine : expectedMessages.get(member)) {
  boolean shouldExpectLogLine =
    acceptedLogLevels.contains(logLine.level) && !logLine.shouldBeIgnoredDueToTimestamp;
  if (shouldExpectLogLine) {
   assertThat(logFileContents).contains(logLine.getMessage());
  } else {
   assertThat(logFileContents).doesNotContain(logLine.getMessage());
  }
 }
}

代码示例来源:origin: sleekbyte/tailor

protected static String getAbsolutePath(String path) throws IOException {
  File file = new File(path);
  if (file.isDirectory()
    && (path.endsWith(".xcodeproj/") || path.endsWith(".xcodeproj"))) {
    return file.getCanonicalPath();
  } else {
    throw new IOException(path + " is not a valid .xcodeproj");
  }
}

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

if (!directory.isDirectory()) {
  throw new IllegalArgumentException("Not a directory: " + directory);
if (!directory.exists() || !child.exists()) {
  return false;
final String canonicalParent = directory.getCanonicalPath();
final String canonicalChild = child.getCanonicalPath();

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

public boolean delete () {
  if (!exists()) {
    return false;
  }
  LocalStorage.removeItem(getCanonicalPath());
  return true;
}

代码示例来源:origin: apache/geode

private void renameJarWithOldNamingConvention(File oldJar) throws IOException {
 Matcher matcher = oldNamingPattern.matcher(oldJar.getName());
 if (!matcher.matches()) {
  throw new IllegalArgumentException("The given jar " + oldJar.getCanonicalPath()
    + " does not match the old naming convention");
 }
 String unversionedJarNameWithoutExtension = matcher.group(1);
 String jarVersion = matcher.group(2);
 String newJarName = unversionedJarNameWithoutExtension + ".v" + jarVersion + ".jar";
 File newJar = new File(this.deployDirectory, newJarName);
 logger.debug("Renaming deployed jar from {} to {}", oldJar.getCanonicalPath(),
   newJar.getCanonicalPath());
 FileUtils.moveFile(oldJar, newJar);
}

代码示例来源:origin: pentaho/pentaho-kettle

private static void createTempDirWithSpecialCharactersInName() throws IOException {
 if ( !TEMP_DIR_WITH_REP_FILE.exists() ) {
  if ( TEMP_DIR_WITH_REP_FILE.mkdir() ) {
   System.out.println( "CREATED: " + TEMP_DIR_WITH_REP_FILE.getCanonicalPath() );
  } else {
   System.out.println( "NOT CREATED: " + TEMP_DIR_WITH_REP_FILE.toString() );
  }
 }
}

代码示例来源:origin: apache/groovy

private int execute(File dir) {
  int fails = 0;
  File[] files = dir.listFiles();
  for (int i = 0; i < files.length; i++) {
    File f = files[i];
    if (f.isDirectory()) {
      fails += execute(f);
    } else if (f.getName().endsWith(".class")) {
      try {
        boolean ok = readClass(f.getCanonicalPath());
        if (!ok) fails++;
      } catch (IOException ioe) {
        log(ioe.getMessage());
        throw new BuildException(ioe);
      }
    }
  }
  return fails;
}

代码示例来源:origin: apache/geode

private void importOnMember(File snapshot, SnapshotFormat format, SnapshotOptions<K, V> options)
  throws IOException, ClassNotFoundException {
 final LocalRegion local = getLocalRegion(region);
 if (getLogger().infoEnabled())
  getLogger().info(String.format("Importing region %s", region.getName()));
 if (snapshot.isDirectory()) {
  File[] snapshots =
    snapshot.listFiles((File f) -> f.getName().endsWith(SNAPSHOT_FILE_EXTENSION));
  if (snapshots == null) {
   throw new IOException("Unable to access " + snapshot.getCanonicalPath());
  } else if (snapshots.length == 0) {
   throw new IllegalArgumentException("Failure to import snapshot: "
     + snapshot.getAbsolutePath() + " contains no valid .gfd snapshot files");
  }
  for (File snapshotFile : snapshots) {
   importSnapshotFile(snapshotFile, options, local);
  }
 } else if (snapshot.getName().endsWith(SNAPSHOT_FILE_EXTENSION)) {
  importSnapshotFile(snapshot, options, local);
 } else {
  throw new IllegalArgumentException("Failure to import snapshot: "
    + snapshot.getCanonicalPath() + " is not .gfd file or directory containing .gfd files");
 }
}

代码示例来源:origin: apache/geode

private File[] getSnapshotFiles(File dir) throws IOException {
 File[] snapshotFiles = dir.listFiles(pathname -> pathname.getName().endsWith(".gfd"));
 if (snapshotFiles == null) {
  throw new IOException("Unable to access " + dir.getCanonicalPath());
 } else if (snapshotFiles.length == 0) {
  throw new FileNotFoundException(
    String.format("No snapshot files found in %s", dir));
 }
 return snapshotFiles;
}

代码示例来源:origin: termux/termux-app

/** Delete a folder and all its content or throw. Don't follow symlinks. */
static void deleteFolder(File fileOrDirectory) throws IOException {
  if (fileOrDirectory.getCanonicalPath().equals(fileOrDirectory.getAbsolutePath()) && fileOrDirectory.isDirectory()) {
    File[] children = fileOrDirectory.listFiles();
    if (children != null) {
      for (File child : children) {
        deleteFolder(child);
      }
    }
  }
  if (!fileOrDirectory.delete()) {
    throw new RuntimeException("Unable to delete " + (fileOrDirectory.isDirectory() ? "directory " : "file ") + fileOrDirectory.getAbsolutePath());
  }
}

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

@Override
public WatchedResource watch( File file ) throws IOException
{
  if ( !file.isDirectory() )
  {
    throw new IllegalArgumentException( format( "File `%s` is not a directory. Only directories can be " +
        "registered to be monitored.", file.getCanonicalPath() ) );
  }
  WatchKey watchKey = file.toPath().register( watchService, OBSERVED_EVENTS, SensitivityWatchEventModifier.HIGH );
  return new WatchedFile( watchKey );
}

代码示例来源:origin: RipMeApp/ripme

/**
 * Determines if the app is running in a portable mode. i.e. on a USB stick
 */
private static boolean portableMode() {
  try {
    File file = new File(new File(".").getCanonicalPath() + File.separator + CONFIG_FILE);
    if (file.exists() && !file.isDirectory()) {
      return true;
    }
  } catch (IOException e) {
    return false;
  }
  return false;
}

相关文章

微信公众号

最新文章

更多