Jump to content
  • Advertisement
Sign in to follow this  
PhlashStudios

Extracting Filename From Filepath in Java

This topic is 4021 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!