org.apache.commons.io.FilenameUtils.normalize()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(1203)

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

FilenameUtils.normalize介绍

[英]Normalizes a path, removing double and single dot path steps.

This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators in the format of the system.

A trailing slash will be retained. A double slash will be merged to a single slash (but UNC names are handled). A single dot path segment will be removed. A double dot will cause that path segment and the one before to be removed. If the double dot has no parent path segment to work with, null is returned.

The output will be the same on both Unix and Windows except for the separator character.

/foo//               -->   /foo/ 
/foo/./              -->   /foo/ 
/foo/../bar          -->   /bar 
/foo/../bar/         -->   /bar/ 
/foo/../bar/../baz   -->   /baz 
//foo//./bar         -->   /foo/bar 
/../                 -->   null 
../foo               -->   null 
foo/bar/..           -->   foo/ 
foo/../../bar        -->   null 
foo/../bar           -->   bar 
//server/foo/../bar  -->   //server/bar 
//server/../bar      -->   null 
C:\foo\..\bar        -->   C:\bar 
C:\..\bar            -->   null 
~/foo/../bar/        -->   ~/bar/ 
~/../bar             -->   null

(Note the file separator returned will be correct for Windows/Unix)
[中]规范化路径,删除双点和单点路径步骤。
此方法将路径规范化为标准格式。输入可以包含Unix或Windows格式的分隔符。输出将包含系统格式的分隔符。
后面的斜杠将被保留。双斜杠将合并为单斜杠(但会处理UNC名称)。将删除单个点路径段。双点将导致删除该路径段和之前的路径段。如果双点没有要使用的父路径段,则返回null
除了分隔符外,Unix和Windows上的输出将相同。

/foo//               -->   /foo/ 
/foo/./              -->   /foo/ 
/foo/../bar          -->   /bar 
/foo/../bar/         -->   /bar/ 
/foo/../bar/../baz   -->   /baz 
//foo//./bar         -->   /foo/bar 
/../                 -->   null 
../foo               -->   null 
foo/bar/..           -->   foo/ 
foo/../../bar        -->   null 
foo/../bar           -->   bar 
//server/foo/../bar  -->   //server/bar 
//server/../bar      -->   null 
C:\foo\..\bar        -->   C:\bar 
C:\..\bar            -->   null 
~/foo/../bar/        -->   ~/bar/ 
~/../bar             -->   null

(注意,返回的文件分隔符对于Windows/Unix是正确的)

代码示例

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

public static boolean isNormalizedDirectoryPathInsideNormalizedParentDirectory(String parent, String subdirectory) {
  final String normalizedParentPath = FilenameUtils.normalize(parent + File.separator);
  final String normalizedSubDirPath = FilenameUtils.normalize(subdirectory + File.separator);
  return StringUtils.isNotBlank(normalizedParentPath) && StringUtils.isNotBlank(normalizedSubDirPath) && normalizedSubDirPath.startsWith(normalizedParentPath);
}
public static boolean isNormalizedPathOutsideWorkingDir(String path) {

代码示例来源:origin: SonarSource/sonarqube

/**
 * Normalize path and replace file separators by forward slash
 */
@CheckForNull
public static String sanitize(@Nullable String path) {
 return FilenameUtils.normalize(path, true);
}

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

private Path getAbsoluteOutputPath(String filename) {
  return root.resolve(FilenameUtils.normalize(filename));
}

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

/**
 * Checks whether two filenames are equal, optionally normalizing and providing
 * control over the case-sensitivity.
 *
 * @param filename1  the first filename to query, may be null
 * @param filename2  the second filename to query, may be null
 * @param normalized  whether to normalize the filenames
 * @param caseSensitivity  what case sensitivity rule to use, null means case-sensitive
 * @return true if the filenames are equal, null equals null
 * @since 1.3
 */
public static boolean equals(
    String filename1, String filename2,
    final boolean normalized, IOCase caseSensitivity) {
  if (filename1 == null || filename2 == null) {
    return filename1 == null && filename2 == null;
  }
  if (normalized) {
    filename1 = normalize(filename1);
    filename2 = normalize(filename2);
    if (filename1 == null || filename2 == null) {
      throw new NullPointerException(
        "Error normalizing one or both of the file names");
    }
  }
  if (caseSensitivity == null) {
    caseSensitivity = IOCase.SENSITIVE;
  }
  return caseSensitivity.checkEquals(filename1, filename2);
}

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

public static boolean isNormalizedPathOutsideWorkingDir(String path) {
    final String normalize = FilenameUtils.normalize(path);
    final String prefix = FilenameUtils.getPrefix(normalize);
    return (normalize != null && StringUtils.isBlank(prefix));
  }
}

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

return normalize(fullFilenameToAdd);
  return normalize(fullFilenameToAdd);
  return normalize(basePath + fullFilenameToAdd);
} else {
  return normalize(basePath + '/' + fullFilenameToAdd);

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

private String getRuleClassSourceFilepath(String ruleClass) throws IOException {
    final String relativeSourceFilename = ruleClass.replaceAll("\\.", Matcher.quoteReplacement(File.separator))
        + ".java";
    final List<Path> foundPathResult = new LinkedList<>();

    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        String path = file.toString();
        if (path.contains("src") && path.endsWith(relativeSourceFilename)) {
          foundPathResult.add(file);
          return FileVisitResult.TERMINATE;
        }
        return super.visitFile(file, attrs);
      }
    });

    if (!foundPathResult.isEmpty()) {
      Path foundPath = foundPathResult.get(0);
      foundPath = root.relativize(foundPath);
      return FilenameUtils.normalize(foundPath.toString(), true);
    }

    return FilenameUtils.normalize(relativeSourceFilename, true);
  }
}

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

public static List<String> findAdditionalRulesets(Path basePath) {
    try {
      List<String> additionalRulesets = new ArrayList<>();
      Pattern rulesetPattern = Pattern.compile("^.+" + Pattern.quote(File.separator) + "pmd-\\w+"
          + Pattern.quote(FilenameUtils.normalize("/src/main/resources/rulesets/"))
          + "\\w+" + Pattern.quote(File.separator) + "\\w+.xml$");
      Files.walkFileTree(basePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
          if (rulesetPattern.matcher(file.toString()).matches()) {
            additionalRulesets.add(file.toString());
          }

          return FileVisitResult.CONTINUE;
        }
      });
      return additionalRulesets;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

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

public static String getRuleSetClasspath(RuleSet ruleset) {
  final String RESOURCES_PATH = "/resources/";
  String filename = FilenameUtils.normalize(StringUtils.chomp(ruleset.getFileName()), true);
  int startIndex = filename.lastIndexOf(RESOURCES_PATH);
  if (startIndex > -1) {
    return filename.substring(startIndex + RESOURCES_PATH.length());
  } else {
    return filename;
  }
}

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

String normPath = FilenameUtils.normalize(path, false);
if (normPath == null) {
  throw new IllegalArgumentException(path);

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

@Override
public boolean removeResource(String name) {
  String resourceName = buildResourceName(name);
  String filePathToRemove = FilenameUtils.normalize(getBaseDirectory(false) + File.separator + resourceName);
  File fileToRemove = new File(filePathToRemove);
  return fileToRemove.delete();
}

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

protected ClassPathResource lookupResourceOnClassPath(String name) {
  if (fileServiceClasspathDirectory != null && !"".equals(fileServiceClasspathDirectory)) {
    try {
      String resourceName = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(fileServiceClasspathDirectory + '/' + name));
      ClassPathResource resource = new ClassPathResource(resourceName);
      if (resource.exists()) {
        return resource;
      }
    } catch (Exception e) {
      LOG.error("Error getting resource from classpath", e);
    }
  }
  return null;
}

代码示例来源:origin: docker-java/docker-java

/**
   * Returns the matching ignore pattern for the given file or null if it should NOT be ignored. Exception rules like "!Dockerfile"
   * will be respected.
   */
  private String effectiveMatchingIgnorePattern(File file) {
    // normalize path to replace '/' to '\' on Windows
    String relativeFilename = FilenameUtils.normalize(FilePathUtil.relativize(baseDirectory, file));
    List<String> matchingPattern = matchingIgnorePatterns(relativeFilename);
    if (matchingPattern.isEmpty()) {
      return null;
    }
    String lastMatchingPattern = matchingPattern.get(matchingPattern.size() - 1);
    return !lastMatchingPattern.startsWith("!") ? lastMatchingPattern : null;
   }
}

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

@Test
public void testNormalizeUnixWin() throws Exception {
  // Normalize (Unix Separator)
  assertEquals("/a/c/", FilenameUtils.normalize("/a/b/../c/", true));
  assertEquals("/a/c/", FilenameUtils.normalize("\\a\\b\\..\\c\\", true));
  // Normalize (Windows Separator)
  assertEquals("\\a\\c\\", FilenameUtils.normalize("/a/b/../c/", false));
  assertEquals("\\a\\c\\", FilenameUtils.normalize("\\a\\b\\..\\c\\", false));
}

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

@Test
public void testNormalize_with_nullbytes() throws Exception {
  try {
    assertEquals("a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("a\\b/c\u0000.txt"));
  } catch (final IllegalArgumentException ignore) {
  }
  try {
    assertEquals("a" + SEP + "b" + SEP + "c.txt", FilenameUtils.normalize("\u0000a\\b/c.txt"));
  } catch (final IllegalArgumentException ignore) {
  }
}

代码示例来源:origin: SonarSource/sonarqube

private boolean evaluateExclusionsFilters(ModuleExclusionFilters moduleExclusionFilters, Path realAbsoluteFile, Path projectRelativePath, Path moduleRelativePath,
 InputFile.Type type) {
 if (!Arrays.equals(moduleExclusionFilters.getExclusionsConfig(type), projectExclusionFilters.getExclusionsConfig(type))) {
  // Module specific configuration
  return moduleExclusionFilters.isExcluded(realAbsoluteFile, moduleRelativePath, type);
 }
 boolean includedByProjectConfiguration = projectExclusionFilters.isExcluded(realAbsoluteFile, projectRelativePath, type);
 if (includedByProjectConfiguration) {
  return true;
 } else if (moduleExclusionFilters.isExcluded(realAbsoluteFile, moduleRelativePath, type)) {
  warnOnce(
   type == Type.MAIN ? CoreProperties.PROJECT_EXCLUSIONS_PROPERTY : CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY,
   FilenameUtils.normalize(projectRelativePath.toString(), true), () -> warnExclusionsAlreadyLogged, () -> warnExclusionsAlreadyLogged = true);
  return true;
 }
 return false;
}

代码示例来源:origin: SonarSource/sonarqube

private boolean evaluateInclusionsFilters(ModuleExclusionFilters moduleExclusionFilters, Path realAbsoluteFile, Path projectRelativePath, Path moduleRelativePath,
 InputFile.Type type) {
 if (!Arrays.equals(moduleExclusionFilters.getInclusionsConfig(type), projectExclusionFilters.getInclusionsConfig(type))) {
  // Module specific configuration
  return moduleExclusionFilters.isIncluded(realAbsoluteFile, moduleRelativePath, type);
 }
 boolean includedByProjectConfiguration = projectExclusionFilters.isIncluded(realAbsoluteFile, projectRelativePath, type);
 if (includedByProjectConfiguration) {
  return true;
 } else if (moduleExclusionFilters.isIncluded(realAbsoluteFile, moduleRelativePath, type)) {
  warnOnce(
   type == Type.MAIN ? CoreProperties.PROJECT_INCLUSIONS_PROPERTY : CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY,
   FilenameUtils.normalize(projectRelativePath.toString(), true), () -> warnInclusionsAlreadyLogged, () -> warnInclusionsAlreadyLogged = true);
  return true;
 }
 return false;
}

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

@Override
public File getResource(String url, FileApplicationType applicationType) {
  String fileName = buildResourceName(url);
  String baseDirectory = getBaseDirectory(true);
  ExtensionResultHolder<String> holder = new ExtensionResultHolder<String>();
  if (extensionManager != null){
    ExtensionResultStatusType result = extensionManager.getProxy().processPathForSite(baseDirectory, fileName, holder);
    if (!ExtensionResultStatusType.NOT_HANDLED.equals(result)) {
      return new File(holder.getResult());
    }
  }
  String filePath = FilenameUtils.normalize(getBaseDirectory(false) + File.separator + fileName);
  return new File(filePath);
}

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

protected File getLocalResource(String resourceName, boolean skipSite) {
  if (skipSite) {
    String baseDirectory = getBaseDirectory(skipSite);
    // convert the separators to the system this is currently run on
    String systemResourcePath = FilenameUtils.separatorsToSystem(resourceName);
    String filePath = FilenameUtils.normalize(baseDirectory + File.separator + systemResourcePath);
    return new File(filePath);
  } else {
    String baseDirectory = getBaseDirectory(true);
    ExtensionResultHolder<String> holder = new ExtensionResultHolder<String>();
    if (extensionManager != null) {
      ExtensionResultStatusType result = extensionManager.getProxy().processPathForSite(baseDirectory, resourceName, holder);
      if (!ExtensionResultStatusType.NOT_HANDLED.equals(result)) {
        return new File(holder.getResult());
      }
    }
    return getLocalResource(resourceName, true);
  }
}

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

private static void setupJaasConfigEntries(String hostServerPrincipal,
    String hostLearnerPrincipal, String hostNamedLearnerPrincipal) {
  String keytabFilePath = FilenameUtils.normalize(KerberosTestUtils.getKeytabFile(), true);
  String jaasEntries = new String(""
      + "QuorumServer {\n"
      + "       com.sun.security.auth.module.Krb5LoginModule required\n"
      + "       useKeyTab=true\n"
      + "       keyTab=\"" + keytabFilePath + "\"\n"
      + "       storeKey=true\n"
      + "       useTicketCache=false\n"
      + "       debug=false\n"
      + "       principal=\"" + KerberosTestUtils.replaceHostPattern(hostServerPrincipal) + "\";\n" + "};\n"
      + "QuorumLearner {\n"
      + "       com.sun.security.auth.module.Krb5LoginModule required\n"
      + "       useKeyTab=true\n"
      + "       keyTab=\"" + keytabFilePath + "\"\n"
      + "       storeKey=true\n"
      + "       useTicketCache=false\n"
      + "       debug=false\n"
      + "       principal=\"" + KerberosTestUtils.replaceHostPattern(hostLearnerPrincipal) + "\";\n" + "};\n"
      + "QuorumLearnerMyHost {\n"
      + "       com.sun.security.auth.module.Krb5LoginModule required\n"
      + "       useKeyTab=true\n"
      + "       keyTab=\"" + keytabFilePath + "\"\n"
      + "       storeKey=true\n"
      + "       useTicketCache=false\n"
      + "       debug=false\n"
      + "       principal=\"" + hostNamedLearnerPrincipal + "\";\n" + "};\n");
  setupJaasConfig(jaasEntries);
}

相关文章

微信公众号

最新文章

更多