How to check file's first name?

I have a situation in which I only have a file's first name(NOT EXTENSION) like 'ms0045' that is coming from database.
Now there may or may not be a file in a known directory with that name.  I want to check if 'ms0045' exists in the directory with any extension or not.

how can i do that.
jaipur07Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
File f = new File ( "filepath/filename.extension" ) ;
String fullFileName = f.getName () ;
String fileName = fullFileName.substring ( 0, fullFileName.lastIndexOf ( "." ) ) ;

should do it, I guess....
0
 
CEHJConnect With a Mentor Commented:
Just iterate the directory

boolean found = false;
String[] files = new File(x).list();
for(int i = 0;i < files.length && !found;i++) {
      found = files[i].getName().startsWith(searchName);
 
}
0
 
jaipur07Author Commented:
startsWith will return all the names like ms00451212', 'ms00455555'

isn't it?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Mayank SAssociate Director - Product EngineeringCommented:
(I mean just getting the name of a file - not searching)
0
 
Mayank SAssociate Director - Product EngineeringCommented:
CEHJ's and mine combined should do both.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> String[] files = new File(x).list();

Use listFiles () if you want to check for only files, not directories.
0
 
CEHJCommented:
>>startsWith will return all the names like ms00451212', 'ms00455555'

Yes. If that's a problem you can do


found = files[i].getName().startsWith(searchName) && searchName.equals(files[i].getName().substring(0, files[i].getName().lastIndexOf('.'));
0
 
CEHJCommented:
(You can remove the first condition before &&)
0
 
jaipur07Author Commented:
let me try and will get back to yo usoon
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Note that there is small optimization in my approach that you don't have to call getName () multiple times saving a method-call :)
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.