(easy) splitting a file name into parts

A

Andy Fish

Hi,

I want to rename a file to have a different extension, but I can't find
anything in java.io.File that has any concept of file extension.

I realise this is probably operating system specific if not
application-specific but since the two biggest OSs use file extensions
extensively(!), I was expecting java.io to provide some utility functions to
manipulate them. FWIW I define the file extension as the bit following the
final dot in the file name but I'm happy to accept someone else's
definition.

Andy
 
C

Chris Smith

Andy said:
I want to rename a file to have a different extension, but I can't find
anything in java.io.File that has any concept of file extension.

I realise this is probably operating system specific if not
application-specific but since the two biggest OSs use file extensions
extensively(!), I was expecting java.io to provide some utility functions to
manipulate them. FWIW I define the file extension as the bit following the
final dot in the file name but I'm happy to accept someone else's
definition.

Well, that last bit seems like a reasonable definition to me. In that
case, see String.lastIndexOf and String.substring for easy ways to
manipulate the extension on a file.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

Nawww

java.io.File.isFile()

If you are parsing the entire unqualified name yourself, and you scan
backwards for . you don't want it to count if it occurs prior to the
last "/", i.e. in one of the directory node names.

You want to scan only the filename proper, e.g. new File ( f ).
getName();
 
J

Jon A. Cruz

Roedy said:
If you are parsing the entire unqualified name yourself, and you scan
backwards for . you don't want it to count if it occurs prior to the
last "/", i.e. in one of the directory node names.

You want to scan only the filename proper, e.g. new File ( f ).
getName();

Exactly.

I had assumed that, since it's been covered many times.

File thing = new File( f );
if ( thing.isFile() )
{
int pos = thing.getName().lastIndexOf( '.' );
if ( pos > -1 )
{
...
}
}

of course, if pos == 0, you now have the tricky problem of deciding if
it's a blank name with only an extension, or if it's a hidden unix-ish
file with no extension.
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top