org.apache.commons.io.FilenameUtils类的使用及代码示例

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

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

FilenameUtils介绍

[英]General filename and filepath manipulation utilities.

When dealing with filenames you can hit problems when moving from a Windows based development machine to a Unix based production machine. This class aims to help avoid those problems.

NOTE: You may be able to avoid using this class entirely simply by using JDK java.io.File objects and the two argument constructor java.io.File#File(java.io.File,java.lang.String).

Most methods on this class are designed to work the same on both Unix and Windows. Those that don't include 'System', 'Unix' or 'Windows' in their name.

Most methods recognise both separators (forward and back), and both sets of prefixes. See the javadoc of each method for details.

This class defines six components within a filename (example C:\dev\project\file.txt):

  • the prefix - C:\
  • the path - dev\project\
  • the full path - C:\dev\project\
  • the name - file.txt
  • the base name - file
  • the extension - txt
    Note that this class works best if directory filenames end with a separator. If you omit the last separator, it is impossible to determine if the filename corresponds to a file or a directory. As a result, we have chosen to say it corresponds to a file.

This class only supports Unix and Windows style names. Prefixes are matched as follows:

Windows: 
a\b\c.txt           --> ""          --> relative 
\a\b\c.txt          --> "\"         --> current drive absolute 
C:a\b\c.txt         --> "C:"        --> drive relative 
C:\a\b\c.txt        --> "C:\"       --> absolute 
\\server\a\b\c.txt  --> "\\server\" --> UNC 
Unix: 
a/b/c.txt           --> ""          --> relative 
/a/b/c.txt          --> "/"         --> absolute 
~/a/b/c.txt         --> "~/"        --> current user 
~                   --> "~/"        --> current user (slash added) 
~user/a/b/c.txt     --> "~user/"    --> named user 
~user               --> "~user/"    --> named user (slash added)

Both prefix styles are matched always, irrespective of the machine that you are currently running on.

Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.
[中]通用文件名和文件路径操作实用程序。
在处理文件名时,从基于Windows的开发机器转移到基于Unix的生产机器时,可能会遇到问题。本课程旨在帮助避免这些问题。
注意:通过使用JDK java,您可以完全避免使用这个类。木卫一。文件对象和双参数构造函数。木卫一。File#File(java.io.File,java.lang.String)。
这个类上的大多数方法都被设计为在Unix和Windows上工作相同。名称中不包含“系统”、“Unix”或“Windows”的。
大多数方法同时识别分隔符(向前和向后)和两组前缀。有关详细信息,请参见每个方法的javadoc。
此类在文件名中定义了六个组件(例如C:\dev\project\file.txt):
*前缀-C:
*路径为-dev\project
*完整路径-C:\dev\project
*名称-文件。文本
*基本名称-文件
*扩展名为-txt
请注意,如果目录文件名以分隔符结尾,则此类的效果最好。如果省略最后一个分隔符,则无法确定文件名是否对应于文件或目录。因此,我们选择说它对应于一个文件。
此类仅支持Unix和Windows样式名称。前缀匹配如下:

Windows: 
a\b\c.txt           --> ""          --> relative 
\a\b\c.txt          --> "\"         --> current drive absolute 
C:a\b\c.txt         --> "C:"        --> drive relative 
C:\a\b\c.txt        --> "C:\"       --> absolute 
\\server\a\b\c.txt  --> "\\server\" --> UNC 
Unix: 
a/b/c.txt           --> ""          --> relative 
/a/b/c.txt          --> "/"         --> absolute 
~/a/b/c.txt         --> "~/"        --> current user 
~                   --> "~/"        --> current user (slash added) 
~user/a/b/c.txt     --> "~user/"    --> named user 
~user               --> "~user/"    --> named user (slash added)

无论您当前运行的机器是什么,这两种前缀样式始终匹配。
代码来源:Excalibur、Alexandria、Tomcat、Commons Utils。

代码示例

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

@Override
  public FileVisitResult visitFile(final Path file,
      final BasicFileAttributes attrs) throws IOException {
    String extension = FilenameUtils.getExtension(file.toString());
    if ("jar".equalsIgnoreCase(extension)) {
      fileVisitor.visitFile(file, attrs);
    }
    return FileVisitResult.CONTINUE;
  }
};

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

/** Maps paths to classes. */
private static Stream<Class<?>> getClasses(URL url, String packageName) throws IOException, URISyntaxException {
  return getPathsInDir(url)
    .stream()
    .filter(path -> "class".equalsIgnoreCase(FilenameUtils.getExtension(path.toString())))
    .<Class<?>>map(path -> {
      try {
        return Class.forName(packageName + "." + FilenameUtils.getBaseName(path.getFileName().toString()));
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
        return null;
      }
    })
    .filter(Objects::nonNull);
}

代码示例来源:origin: jenkinsci/jenkins

@DataBoundConstructor
public FileParameterValue(String name, FileItem file) {
  this(name, file, FilenameUtils.getName(file.getName()));
}

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

/**
 * Converts all separators to the system separator.
 *
 * @param path  the path to be changed, null ignored
 * @return the updated path
 */
public static String separatorsToSystem(final String path) {
  if (path == null) {
    return null;
  }
  if (isSystemWindows()) {
    return separatorsToWindows(path);
  } else {
    return separatorsToUnix(path);
  }
}

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

/**
 * Gets the base name, minus the full path and extension, from a full filename.
 * <p>
 * This method will handle a file in either Unix or Windows format.
 * The text after the last forward or backslash and before the last dot is returned.
 * <pre>
 * a/b/c.txt --&gt; c
 * a.txt     --&gt; a
 * a/b/c     --&gt; c
 * a/b/c/    --&gt; ""
 * </pre>
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to query, null returns null
 * @return the name of the file without the path, or an empty string if none exists. Null bytes inside string
 * will be removed
 */
public static String getBaseName(final String filename) {
  return removeExtension(getName(filename));
}

代码示例来源: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: gocd/gocd

public String getFullViewPath() {
  if (StringUtils.isBlank(assetRoot)) {
    return viewPath;
  }
  int positionOfQueryParamStart = viewPath.indexOf('?');
  String viewPathWithoutQueryParams = positionOfQueryParamStart == -1 ? viewPath : viewPath.substring(0, positionOfQueryParamStart);
  String queryParams = positionOfQueryParamStart == -1 ? "" : viewPath.substring(positionOfQueryParamStart);
  return URI.create(FilenameUtils.separatorsToUnix(Paths.get(assetRoot, viewPathWithoutQueryParams).toString()) + queryParams).normalize().toString();
}

代码示例来源:origin: de.digitalcollections/digitalcollections-core-model-api

public static MimeType fromURI(URI uri) {
 try {
  return fromFilename(Paths.get(uri).toString());
 } catch (FileSystemNotFoundException e) {
  // For non-file URIs, try to guess the MIME type from the URL path, if possible
  return fromExtension(FilenameUtils.getExtension(uri.toString()));
 }
}

代码示例来源:origin: kiegroup/appformer

public void init(String bundleParam) {
  if (bundleParam != null) {
    Path fullPath = Paths.get(bundleParam);
    File bundleFile = fullPath.toFile();
    if (bundleFile.exists()) {
      bundlePath = bundleFile.toPath().getParent();
      bundleName = FilenameUtils.getBaseName(bundleFile.getName());
    } else {
      LOG.error("Invalid bundle '" + bundleParam + "': file doesn't exist");
    }
  }
}

代码示例来源:origin: net.jangaroo/jangaroo-maven-plugin

private static File relativePathForProject(File workspaceDir, MavenProject project, String localPathToSrc) throws MojoExecutionException {
  Path rootPath = workspaceDir.toPath().normalize();
  Path path = Paths.get(project.getBuild().getDirectory() + localPathToSrc);
  Path relativePath = rootPath.relativize(path);
  String relativePathString = FilenameUtils.separatorsToUnix(relativePath.toString());
  if (relativePathString.isEmpty()) {
   throw new MojoExecutionException("Cannot handle project because not relative path to root workspace could be build");
  }
  return new File(relativePathString);
 }
}

代码示例来源:origin: hyperledger/fabric-sdk-java

Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, true);
  relativePath = FilenameUtils.separatorsToUnix(relativePath);
  childrenFiles = org.apache.commons.io.FileUtils.listFiles(chaincodeMetaInf, null, true);
    final String relativePath = Paths.get("META-INF", metabase.relativize(childFile.toURI()).getPath()).toString();

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

int prefix = FilenameUtils.getPrefixLength(name);
  if (prefix > -1) {
    name = name.substring(prefix);
  name = FilenameUtils.normalize(FilenameUtils.getName(name));
Path outputFile = outputDir.resolve(name);
if (Files.exists(outputFile)) {
  outputFile = outputDir.resolve(UUID.randomUUID().toString()+"-"+name);
Files.createDirectories(outputFile.getParent());
Files.copy(stream, outputFile);

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

String tempFileSuffix = tika ? null : "." + FilenameUtils.getExtension(fileName);
String tempFilePrefix = UUID.randomUUID().toString();
Path tempFile = Files.createTempFile(tempFilePrefix, tempFileSuffix);
try {
  InputStream in = new PushbackInputStream(new BufferedInputStream(inputStream));
  try (OutputStream out = new FileOutputStream(tempFile.toFile())) {
    IOUtils.copyLarge(in, out);
  String contentType = Files.probeContentType(tempFile);
  if (contentType == null) {
    if (LOGGER.isLoggable(Level.WARNING)) {
    if (FilenameUtils.wildcardMatch(contentType.toLowerCase(), accept)) {
      accepted = true;
      if (LOGGER.isLoggable(Level.FINE)) {
    Files.delete(tempFile);
          tempFile.toAbsolutePath()), ex);
      try {
        tempFile.toFile().deleteOnExit();

代码示例来源: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: apache/geode

(InternalConfigurationPersistenceService) getConfigurationPersistenceService();
if (zipFileName != null) {
 Path tempDir = Files.createTempDirectory("temp");
 Path exportedDir = tempDir.resolve("cluster_config");
 Path zipFile = tempDir.resolve(FilenameUtils.getName(zipFileName));
 try {
  for (Configuration config : configPersistenceService.getEntireConfiguration().values()) {
   configPersistenceService.writeConfigToFile(config, exportedDir.toFile());
  logger.error("unable to export configuration.", e);
 } finally {
  FileUtils.deleteQuietly(tempDir.toFile());

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

/**
 * Similar to {@link Path#relativize(Path)} except that:
 *   <ul>
 *   <li>null is returned if file is not a child of dir
 *   <li>the resulting path is converted to use Unix separators
 *   </ul> 
 * @since 6.0
 */
@CheckForNull
public String relativePath(Path dir, Path file) {
 Path baseDir = dir.normalize();
 Path path = file.normalize();
 if (!path.startsWith(baseDir)) {
  return null;
 }
 try {
  Path relativized = baseDir.relativize(path);
  return FilenameUtils.separatorsToUnix(relativized.toString());
 } catch (IllegalArgumentException e) {
  return null;
 }
}

代码示例来源:origin: ata4/disunity

public SerializedFileReader(Path file) throws IOException {
  String fileName = file.getFileName().toString();
  String fileExt = FilenameUtils.getExtension(fileName);
  // load audio buffer if existing
  readResourceStream(file.resolveSibling(fileName + ".streamingResourceImage"));
  readResourceStream(file.resolveSibling(fileName + ".resS"));
  // join split serialized files before loading
  if (fileExt.startsWith("split")) {
    L.fine("Found split serialized file");
    fileName = FilenameUtils.removeExtension(fileName);
    List<Path> parts = new ArrayList<>();
    int splitIndex = 0;
    // collect all files with .split0 to .splitN extension
    while (true) {
      String splitName = String.format("%s.split%d", fileName, splitIndex);
      Path part = file.resolveSibling(splitName);
      if (Files.notExists(part)) {
        break;
      }
      L.log(Level.FINE, "Adding splinter {0}", part.getFileName());
      splitIndex++;
      parts.add(part);
    }
    // load all parts to one byte buffer
    in = DataReaders.forByteBuffer(ByteBufferUtils.load(parts));
  } else {
    in = DataReaders.forFile(file, READ);
  }
}

代码示例来源:origin: allure-framework/allure2

@Override
public Attachment visitAttachmentFile(final Path attachmentFile) {
  final RandomUidContext context = configuration.requireContext(RandomUidContext.class);
  return attachments.computeIfAbsent(attachmentFile, file -> {
    final String uid = context.getValue().get();
    final String realType = probeContentType(file);
    final String extension = Optional.of(getExtension(file.toString()))
        .filter(s -> !s.isEmpty())
        .map(s -> "." + s)
        .orElseGet(() -> getExtensionByMimeType(realType));
    final String source = uid + (extension.isEmpty() ? "" : extension);
    final Long size = getFileSizeSafe(file);
    return new Attachment()
        .setUid(uid)
        .setName(file.getFileName().toString())
        .setSource(source)
        .setType(realType)
        .setSize(size);
  });
}

代码示例来源:origin: CloudSlang/cloud-slang

private static Set<String> readChangedFilesFromSource(String filePath) throws IOException {
  String normalizedPath = FilenameUtils.normalize(filePath);
  if (!get(normalizedPath).isAbsolute()) {
    throw new RuntimeException(MESSAGE_ERROR_LOADING_SMART_MODE_CONFIG_FILE +
        " Path[" + normalizedPath + "] is not an absolute path.");
  }
  if (!isRegularFile(get(normalizedPath), NOFOLLOW_LINKS)) {
    throw new RuntimeException(MESSAGE_ERROR_LOADING_SMART_MODE_CONFIG_FILE +
        " Path[" + normalizedPath + "] does not lead to a regular file.");
  }
  return ArgumentProcessorUtils.loadChangedItems(normalizedPath);
}

代码示例来源:origin: AppliedEnergistics/Applied-Energistics-2

private boolean process( final Path root, final Path file )
  String relative = root.relativize( file ).toString();
  if( !"json".equals( FilenameUtils.getExtension( file.toString() ) ) || relative.startsWith( "_" ) )
  String name = FilenameUtils.removeExtension( relative ).replaceAll( "\\\\", "/" );
  ResourceLocation key = new ResourceLocation( this.ctx.getModId(), name );
  try
    reader = Files.newBufferedReader( file );
    JsonObject json = JsonUtils.fromJson( GSON, reader, JsonObject.class );
    if( json.has( "conditions" ) && !CraftingHelper.processConditions( JsonUtils.getJsonArray( json, "conditions" ), this.ctx ) )

相关文章