• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Substring Exception

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic