# Extracting Filename From Filepath in Java

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

## 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 on other sites
new File("C:\Documents and Settings\user\My Documents\My Pictures\picture.bmp").getName();

?

##### Share on other sites
*Puts on dunce cap walks into corner*

##### Share on other sites
Quote:
 Original post by PhlashStudiosBut 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 advanceThis 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.

1. 1
2. 2
frob
16
3. 3
4. 4
5. 5

• 13
• 13
• 60
• 14
• 15
• ### Forum Statistics

• Total Topics
632124
• Total Posts
3004248

×