Extract Filename

N

Noodle

Hi There,

Can anyone tell me what is the best way to seperate a filename and a
path so I'm left with 2 strings.

e.g.
Turn this input: "C:\path\to\my\file.txt" into:
String path = "C:\path\to\my";
String file = "file.txt";

as well as turning this: "/path/to/my/file.txt"
String path = "/path/to/my";
String file = "file.txt";

TIA
 
G

Gordon Beaton

Can anyone tell me what is the best way to seperate a filename and a
path so I'm left with 2 strings.

Intuitively I would use methods in java.lang.String to find the last
instance of the separator character, then create substrings around
that point.

However there are also methods in java.io.File that will do exactly
this for you: getName() and getParent().

/gordon
 
T

Tim Slattery

Noodle said:
Hi There,

Can anyone tell me what is the best way to seperate a filename and a
path so I'm left with 2 strings.

e.g.
Turn this input: "C:\path\to\my\file.txt" into:
String path = "C:\path\to\my";
String file = "file.txt";

as well as turning this: "/path/to/my/file.txt"
String path = "/path/to/my";
String file = "file.txt";

String fullPath = new String("/path/to/my/file.txt");
int i = fullPath.lastIndexOf("/");
String path = fullPath.substring(0, i);
String file = fullPath.substring(i + 1);

--
Tim Slattery
(e-mail address removed)
 
S

Steve W. Jackson

Tim Slattery said:
String fullPath = new String("/path/to/my/file.txt");
int i = fullPath.lastIndexOf("/");
String path = fullPath.substring(0, i);
String file = fullPath.substring(i + 1);

--
Tim Slattery
(e-mail address removed)

As was pointed out in an earlier reply, there's another way that IMHO is
most definitely better than anything involving lastIndexOf since the OP
specifically shows x-plat interest. That's the use of the java.io.File
class instead.
 
N

Noodle

Tim said:
String fullPath = new String("/path/to/my/file.txt");
int i = fullPath.lastIndexOf("/");
String path = fullPath.substring(0, i);
String file = fullPath.substring(i + 1);

Thank you everyone for your speedy reply's. I've based my code on Tim's
reply and it works well...

String fullPath = "/path/to/my/file.txt";
int i = fullPath.lastIndexOf(System.getProperty("file.separator"));
String path = fullPath.substring(0, i);
String file = fullPath.substring(i + 1);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top