Java拆分路径..?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4431911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:23:15  来源:igfitidea点击:

Java split the path..?

javastringpathsplit

提问by yuvaraj

This is the input as string:

这是作为字符串的输入:

"C:\jdk1.6.0\bin\program1.java"

I need output as:

我需要输出为:

Path-->C:\jdk1.6.0\bin\
file--->program1.java
extension--->.java

Watch out the "\" char. I easily got output for "/".

注意“\”字符。我很容易得到“/”的输出。

回答by Kurt Kaylor

The Fileclass gives you everything you need:

文件类为您提供您所需要的一切:

    File f = new File("C:\jdk1.6.0\bin\program1.java");
    System.out.println("Path-->" + f.getParent());
    System.out.println("file--->" + f.getName());       
    int idx = f.getName().lastIndexOf('.');
    System.out.println("extension--->" + ((idx > 0) ? f.getName().substring(idx) : "") );

EDIT: Thanks Dave for noting that String.lastIndexOf will return -1 if File.getName does not contain '.'.

编辑:感谢 Dave 注意到如果 File.getName 不包含“.”,则 String.lastIndexOf 将返回 -1。

回答by Dave Jarvis

Since Java's Fileclass does not support probing for the extension, I suggest you create a subclass of Filethat provides this ability:

由于 Java 的File类不支持扩展的探测,我建议您创建一个File提供此功能的子类:

package mypackage;

/**
 * Enhances java.io.File functionality by adding extension awareness.
 */
public class File extends java.io.File {
  /**
   * Returns the characters after the last period.
   *
   * @return An empty string if there is no extension.
   */    
  public String getExtension() {
    String name = getName();
    String result = "";
    int index = name.lastIndexOf( '.' );

    if( index > 0 ) {
      result = name.substring( index );
    }

    return result;
  }
}

Now simply substitute your version of File for Java's version and, when combined with Kurt's answer, gives you everything you need.

现在只需将您的 File 版本替换为 Java 的版本,并结合 Kurt 的回答,为您提供所需的一切。

Notice that using a subclass is ideal because if you wanted to change the behaviour (due to a different operating system using a different extension delimiter token), you need only update a single method and your entire application continues to work. (Or if you need to fix a bug, such as trying to execute str.substring( -1 ).)

请注意,使用子类是理想的,因为如果您想更改行为(由于不同的操作系统使用不同的扩展分隔符标记),您只需要更新一个方法,您的整个应用程序就可以继续工作。(或者,如果您需要修复错误,例如尝试执行str.substring( -1 ).)

In other words, if you extract a file extension in more than one placein your code base, you have made a mistake.

换句话说,如果您在代码库中的多个位置提取文件扩展名,那么您就犯了一个错误。

Going further, if you wanted to completely abstract the knowledge of the file type (because some operating systems might not use the .separator), you could write:

更进一步,如果您想完全抽象文件类型的知识(因为某些操作系统可能不使用.分隔符),您可以编写:

/**
 * Enhances java.io.File functionality by adding extension awareness.
 */
public class File extends java.io.File {
  public File( String filename ) {
    super( filename );
  }

  /**
   * Returns true if the file type matches the given type.
   */
  public boolean isType( String type ) {
    return getExtension().equals( type );
  }

  /**
   * Returns the characters after the last period.
   *
   * @return An empty string if there is no extension.
   */    
  private String getExtension() {
    String name = getName();
    String result = "";
    int index = name.lastIndexOf( '.' );

    if( index > 0 ) {
      result = name.substring( index );
    }

    return result;
  }
}

I would consider this a much more robust solution. This would seamlessly allow substituting a more advanced file type detection mechanism (analysis of file contents to determine the type), without having to change the calling code. Example:

我会认为这是一个更强大的解决方案。这将无缝地允许替换更高级的文件类型检测机制(分析文件内容以确定类型),而无需更改调用代码。例子:

File file = new File( "myfile.txt" );
if( file.isType( "png" ) ) {
  System.out.println( "PNG image found!" );
}

If a user saved "myfile.png" as "myfile.txt", the image would still be processed because the advanced version (not shown here) would look for the "PNG" marker that starts every single PNG file in the (cyber) world.

如果用户将“myfile.png”保存为“myfile.txt”,该图像仍将被处理,因为高级版本(此处未显示)会查找“PNG”标记,该标记开始(网络)中的每个 PNG 文件世界。

回答by Rhysyngsun

Consider using an existing solution instead of rolling your own and introducing more code that needs to be tested. FilenameUtils from Apache Commons IO is one example:

考虑使用现有的解决方案,而不是推出自己的解决方案并引入更多需要测试的代码。来自 Apache Commons IO 的 FilenameUtils 就是一个例子:

http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FilenameUtils.html

http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FilenameUtils.html

回答by Rahul Jawale

You need to compensate for the double slashes returned in Path (if it has been programmatically generated).

您需要补偿 Path 中返回的双斜线(如果它已通过编程生成)。

//Considering that strPath holds the Path String
String[] strPathParts = strPath.split("\\");

//Now to check Windows Drive
System.out.println("Drive Name : "+strPathParts[0]);