• Post Reply Bookmark Topic Watch Topic
  • New Topic

Substring Exception  RSS feed

 
Rohit Kumar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a String which is holding a file path like(C:\Documents and Settings\bkmal\Desktop\application.pdf)

I need to get only the file name like(application.pdf in the above fielPath).


String filePath = "C:\Documents and Settings\bkmal\Desktop\application.pdf";

String onlyfileName= filePath.substring((filePath.lastIndexOf("/")),filePath.length());

when I do this I get the following exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1

what am I doing wrong?? any suggestions
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your arguments for the substring function are the last index of "/" and the length of the string (note: you can omit this one; if you only pass one argument, the remainder of the string is returned).

Now, if the "/" cannot be found, lastIndexOf returns -1. Now here's a question for you: where in your string is the "/"?


Basically, the string you have represents a file. Therefore, it makes sense to use a File object:

This way it doesn't matter if the string uses / or \; both will work. Plus the file has lots of other neat features.
 
Charles McGuire
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good tip on use of File, Rob.

If any further parsing of the directories is needed, consider using the file separator property. That way it works wherever it is deployed.

System.getProperty("file.separator") will equal "/" or "\" depending if it is a *nix or doze platform.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!