Sign in to follow this  

Extracting Filename From Filepath in Java

This topic is 3860 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I have a string containing a filepath and I want to extract the filename (with extension) how would I do that. Originally I did this: String filepath = "C:\Documents and Settings\user\My Documents\My Pictures\picture.bmp"; String[] buf = filepath.split("\\"); String filename = buf[buf.length-1]; But I keep getting an exception that I think has something to do with the split("\\")...Assuming I have to keep the filepath in that format, any ideas? /thanks in advance This is the error: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 ^

Share this post


Link to post
Share on other sites
Quote:
Original post by PhlashStudios
But I keep getting an exception that I think has something to do with the split("\\")...Assuming I have to keep the filepath in that format, any ideas?

/thanks in advance

This is the error:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
^


Just so that you understand regexes better: When you write "\\", that code represents the string that consists of one character: just a single backslash. This is because you are escaping the backslash character, so that *the java compiler* doesn't interpret it as the start of a "special" sequence (such as the \n combination that represents a newline). However, regex syntax also involves special sequences that start with backslashes, and therefore if you want a regex that matches a backslash, *the regex engine* has to see an escape sequence - i.e., two backslashes. That means you need *four* backslashes in your code, so that the compiler will do its escaping and generate code to make a string with two backslashes, so that the regex engine will do *its* escaping and generate a Matcher object that matches one backslash.

Share this post


Link to post
Share on other sites

This topic is 3860 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this