Java 分割了路径..?

发布于 2024-10-07 02:33:50 字数 219 浏览 0 评论 0 原文

这是字符串输入:

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

我需要输出为:

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

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

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 "/".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蓝天 2024-10-14 02:33:50

File 类为您提供所需的一切:

    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) : "") );

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

The File class 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 '.'.

睫毛上残留的泪 2024-10-14 02:33:50

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

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

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:

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

迷迭香的记忆 2024-10-14 02:33:50

由于 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;
  }
}

现在只需将您的 File 版本替换为 Java 的版本,然后与库尔特的答案相结合,可以为您提供所需的一切。

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

换句话说,如果您在多个位置提取文件扩展名< /em> 在你的代码库中,你犯了一个错误。

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

/**
 * 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;
  }
}

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

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

如果用户将“myfile.png”保存为“myfile.txt”,则仍会处理该图像,因为高级版本(此处未显示)将查找在 (网络)世界。

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

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.

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 ).)

In other words, if you extract a file extension in more than one place in 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.

ぽ尐不点ル 2024-10-14 02:33:50

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

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

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

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

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

//Now to check Windows Drive
System.out.println("Drive Name : "+strPathParts[0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文