Solved

# java string.split file directory path

Posted on 2011-03-01
Medium Priority
2,732 Views
Hello

Trying to return the file name from a the directory path:

Its not splitting the string at all.

public String getFilenameFromFile(String file)
{
String delims = "[\\]"; < -- when I debug this is the symbol seperating the folders
String[] tokens = file.split(delims);
int num = tokens.length;
String lfilename = tokens[num].toString();
return filename;
}

0
Question by:AndyC1000
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 3

LVL 40

Expert Comment

ID: 35013841
can you print the 'file' variable contents?
0

LVL 47

Expert Comment

ID: 35013852

http://stackoverflow.com/questions/1099859/how-to-split-a-path-platform-independent

offer
this solution:

String[] subDirs = path.split(Pattern.quote(File.separator));
0

LVL 47

Accepted Solution

for_yan earned 332 total points
ID: 35013876
And I tested it

String[] subDirs = path.split(Pattern.quote(File.separator));

and it really works

"C:\\temt\\text.txt"  -->

C:
temt
text.t

0

LVL 92

Assisted Solution

objects earned 168 total points
ID: 35013878
try this:

File f = new File(file);
String filename = f.getName();
0

LVL 47

Assisted Solution

for_yan earned 332 total points
ID: 35013879
And I tested it

String[] subDirs = path.split(Pattern.quote(File.separator));

and it really works

"C:\\temt\\text.txt"  -->

C:
temt
text.txt
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
###### Suggested Courses
Course of the Month9 days, 18 hours left to enroll