开发者

Java split the path..?

This is the input as string:

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

I nee开发者_如何学God output as:

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

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


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


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


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.


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]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜