• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 265
  • Last Modified:

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.
0
jaipur07
Asked:
jaipur07
  • 5
  • 4
  • 2
2 Solutions
 
CEHJCommented:
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
 
Mayank SAssociate 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
 
jaipur07Author Commented:
startsWith will return all the names like ms00451212', 'ms00455555'

isn't it?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
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

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 5
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now