12

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

4
  • 2
    What code do you have so far? Commented Dec 13, 2010 at 18:04
  • Going after your comment to @Kurt solution it's homework. Feel free to remove this tag. Commented Dec 13, 2010 at 18:28
  • Its not a homework. I splited this using indexOf() and subString(). I just need why we cant able to split this using split()...? Still I didn't get answer for this. Commented Dec 13, 2010 at 18:34
  • @yuvaraj, No, I should apologize for wrong suggestion) Commented Dec 13, 2010 at 18:42

4 Answers 4

21

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

Sign up to request clarification or add additional context in comments.

5 Comments

If you're trying to limit yourself to String.split, then take note of how Kurt is using lastIndexOf()
File f = new File( "C:\\jdk1.6.0\\doc\\readme" );. What does your code do in that case?
Fails. String.lastIndexOf will return -1 ;-)
Your answer is really helpful. I'm sorry to ask this again. why we cant able to split this using string.split(regex r)..?
But this may be Totally inefficent way of doing it.Let consider a scenario that you are going through the loop then each time you a leaking one file object. i may be wrong .any suggustion are most wellcome.
9

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

5 Comments

May be you are correct. All I want to know is why we cant able to split this using String.split()..?
I, personally, tend to be wary of utility classes; they smack of functional, not Object-Oriented programming. The Apache Commons package should have extended File directly to enhance its behaviour, as I have shown.
@Dave Jarvis: I can't dispute that it is a functional API and at the end of the day it's up to personal taste. For me, it comes down to the benefits of maintainability over API implementation.
@yuvaraj: Nothing is stopping you from using String.split(), but as Dave Jarvis responded to your post above, it's a rather limited and crazy approach. Any of the other solutions on this page are more viable and maintainable.
I wish I could up-vote twice! You just saved me maybe 30 minutes! I disagree with Dave in this case. Here a utility class makes more sense than extending the class. Imagine if Apache extended File for utility purposes, and some other company extend File for utility purposes, but then you need to access functionality from both of these utility classes. You would have to dangerously cast your Apache File back to a java.lang.File in order to use the functionality from the other company's File utility class. And vice versa if you need to subsequently get at some of the Apache gizmos again.
3

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.

3 Comments

May be you are correct. All I want to know is why we cant able to split this using String.split()..?
I am unable to split the String using String.split() using "\\" as a delimiter. The entire string is return to the first element of the array. I dont know why.. Could u pls write the code to for that..?
@yuvaraj: What I am saying is that String.split() is not the correct way to write this functionality. You really should use indexOf() as has been mentioned.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.