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

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

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

FilenameUtils.getName介绍

[英]Gets the name minus the path from a full filename.

This method will handle a file in either Unix or Windows format. The text after the last forward or backslash is returned.

a/b/c.txt --> c.txt 
a.txt     --> a.txt 
a/b/c     --> c 
a/b/c/    --> ""

The output will be the same irrespective of the machine that the code is running on.
[中]从完整文件名中获取名称减去路径。
此方法将处理Unix或Windows格式的文件。返回最后一个正斜杠或反斜杠后的文本。

a/b/c.txt --> c.txt 
a.txt     --> a.txt 
a/b/c     --> c 
a/b/c/    --> ""

无论代码在哪台机器上运行,输出都是相同的。

代码示例

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

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

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

private static String getFileName(URI uri) {
 if (uri == null) {
  return null;
 }
 String name = FilenameUtils.getName(uri.getPath());
 return name;
}

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

private static String getFileName(URI uri) {
 if (uri == null) {
  return null;
 }
 String name = FilenameUtils.getName(uri.getPath());
 return name;
}

代码示例来源:origin: org.apache.commons/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 --> c
 * a.txt     --> a
 * a/b/c     --> c
 * a/b/c/    --> ""
 * </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
 */
public static String getBaseName(String filename) {
  return removeExtension(getName(filename));
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Gets the parent of the file at a path.
 *
 * @param path The path
 * @return the parent path of the file; this is "/" if the given path is the root
 * @throws InvalidPathException if the path is invalid
 */
public static String getParent(String path) throws InvalidPathException {
 String cleanedPath = cleanPath(path);
 String name = FilenameUtils.getName(cleanedPath);
 String parent = cleanedPath.substring(0, cleanedPath.length() - name.length() - 1);
 if (parent.isEmpty()) {
  // The parent is the root path.
  return AlluxioURI.SEPARATOR;
 }
 return parent;
}

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

private boolean segmentsFilePredicate( String fileName )
  {
    return FilenameUtils.getName( fileName ).startsWith( IndexFileNames.SEGMENTS );
  }
}

代码示例来源:origin: simpligility/android-maven-plugin

private String getFullPathWithName( String filename )
{
  return FilenameUtils.getFullPath( filename ) + FilenameUtils.getName( filename );
}

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

public static List<File> extractFilesInLibDirAndReturnFiles(File aJarFile, Predicate<JarEntry> extractFilter, File outputTmpDir) {
  List<File> newClassPath = new ArrayList<>();
  try (JarFile jarFile = new JarFile(aJarFile)) {
    List<File> extractedJars = jarFile.stream()
        .filter(extractFilter)
        .map(jarEntry -> {
          String jarFileBaseName = FilenameUtils.getName(jarEntry.getName());
          File targetFile = new File(outputTmpDir, jarFileBaseName);
          return extractJarEntry(jarFile, jarEntry, targetFile);
        })
        .collect(Collectors.toList());
    // add deps in dir specified by `libDirManifestKey`
    newClassPath.addAll(extractedJars);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  return newClassPath;
}

代码示例来源:origin: joelittlejohn/jsonschema2pojo

public static String getNodeName(String filePath, GenerationConfig config) {
  try {
    String fileName = FilenameUtils.getName(URLDecoder.decode(filePath, "UTF-8"));
    String[] extensions = config.getFileExtensions() == null ? new String[] {} : config.getFileExtensions();
    
    boolean extensionRemoved = false;
    for (int i = 0; i < extensions.length; i++) {
      String extension = extensions[i];
      if (extension.length() == 0) {
        continue;
      }
      if (!extension.startsWith(".")) {
        extension = "." + extension;
      }
      if (fileName.endsWith(extension)) {
        fileName = removeEnd(fileName, extension);
        extensionRemoved = true;
        break;
      }
    }
    if (!extensionRemoved) {
      fileName = FilenameUtils.getBaseName(fileName);
    }
    return fileName;
  } catch (UnsupportedEncodingException e) {
    throw new IllegalArgumentException(String.format("Unable to generate node name from URL: %s", filePath), e);
  }
}

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

protected String getFileName(String fileToDownloadLocation, HttpResponse response) {
 for (Header header : response.getAllHeaders()) {
  Optional<String> fileName = httpHelper.getFileNameFromContentDisposition(header.getName(), header.getValue());
  if (fileName.isPresent()) {
   return fileName.get();
  }
 }
 log.info("Cannot extract file name from http headers. Found headers: ");
 for (Header header : response.getAllHeaders()) {
  log.info(header.getName() + '=' + header.getValue());
 }
 String fullFileName = FilenameUtils.getName(fileToDownloadLocation);
 return isBlank(fullFileName) ? downloader.randomFileName() : trimQuery(fullFileName);
}

代码示例来源:origin: deeplearning4j/nd4j

/**
 * Get a temp file from the classpath, and (optionally) place it in the specified directory<br>
 * Note that:<br>
 * - If the directory is not specified, the file is copied to the default temporary directory, using
 * {@link Files#createTempFile(String, String, FileAttribute[])}. Consequently, the extracted file will have a
 * different filename to the extracted one.<br>
 * - If the directory *is* specified, the file is copied directly - and the original filename is maintained
 *
 * @param rootDirectory May be null. If non-null, copy to the specified directory
 * @return the temp file
 * @throws IOException If an error occurs when files are being copied
 * @see #getTempFileFromArchive(File)
 */
public File getTempFileFromArchive(File rootDirectory) throws IOException {
  InputStream is = getInputStream();
  File tmpFile;
  if(rootDirectory != null){
    //Maintain original file names, as it's going in a directory...
    tmpFile = new File(rootDirectory, FilenameUtils.getName(path));
  } else {
    tmpFile = Files.createTempFile(FilenameUtils.getName(path), "tmp").toFile();
  }
  tmpFile.deleteOnExit();
  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
  IOUtils.copy(is, bos);
  bos.flush();
  bos.close();
  return tmpFile;
}

代码示例来源:origin: deeplearning4j/dl4j-examples

int idx = url.indexOf("fulltext/");
String year = url.substring(idx + 9, idx + 9 + 4);
String filename = FilenameUtils.getName(url);

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

@Test
public void testGetName() {
  assertEquals(null, FilenameUtils.getName(null));
  assertEquals("noseperator.inthispath", FilenameUtils.getName("noseperator.inthispath"));
  assertEquals("c.txt", FilenameUtils.getName("a/b/c.txt"));
  assertEquals("c", FilenameUtils.getName("a/b/c"));
  assertEquals("", FilenameUtils.getName("a/b/c/"));
  assertEquals("c", FilenameUtils.getName("a\\b\\c"));
}

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

public static String getBaseName(LocalResource lr) {
 return FilenameUtils.getName(lr.getResource().getFile());
}

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

public String getBaseName(LocalResource lr) {
 return FilenameUtils.getName(lr.getResource().getFile());
}

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

@Test
public void testInjectionFailure() {
  try {
    assertEquals("c", FilenameUtils.getName("a\\b\\\u0000c"));
  } catch (final IllegalArgumentException ignore) {
  }
}

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

public static String getValidFilename(String filename) {
  if (LangUtils.isValueBlank(filename)) {
    return null;
  }
  if (isSystemWindows()) {
    if (!filename.contains("\\\\")) {
      String[] parts = filename.substring(FilenameUtils.getPrefixLength(filename)).split(Pattern.quote(File.separator));
      for (String part : parts) {
        if (INVALID_FILENAME_PATTERN.matcher(part).find()) {
          throw new FacesException("Invalid filename: " + filename);
        }
      }
    }
    else {
      throw new FacesException("Invalid filename: " + filename);
    }
  }
  String name = FilenameUtils.getName(filename);
  String extension = FilenameUtils.EXTENSION_SEPARATOR_STR + FilenameUtils.getExtension(filename);
  if (extension.equals(FilenameUtils.EXTENSION_SEPARATOR_STR)) {
    throw new FacesException("File must have an extension");
  }
  else if (name.isEmpty() || extension.equals(name)) {
    throw new FacesException("Filename can not be the empty string");
  }
  return name;
}

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

FetchHandler getHandler(FetchTask task, String pipelineName) {
  return isNotEmpty(task.getRawSrcdir()) ? new DirHandler(task.getRawSrcdir(), task.destOnAgent(pipelineName)) : new FileHandler(
      task.artifactDest(pipelineName, FilenameUtils.getName(task.getRawSrcfile())), task.getSrc());
}

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

private ComponentImpl buildFile(ScannerReport.Component component) {
 String key = keyGenerator.generateKey(rootComponent.getKey(), component.getProjectRelativePath());
 String publicKey = publicKeyGenerator.generateKey(rootComponent.getKey(), component.getProjectRelativePath());
 return ComponentImpl.builder(Component.Type.FILE)
  .setUuid(uuidSupplier.apply(key))
  .setDbKey(key)
  .setKey(publicKey)
  .setName(component.getProjectRelativePath())
  .setShortName(FilenameUtils.getName(component.getProjectRelativePath()))
  .setStatus(convertStatus(component.getStatus()))
  .setDescription(trimToNull(component.getDescription()))
  .setReportAttributes(createAttributesBuilder(component.getRef(), component.getProjectRelativePath(), scmBasePath).build())
  .setFileAttributes(createFileAttributes(component))
  .build();
}

相关文章