Reputation: 2500
I store file names of images in my database(user_id.extension, for example 14.png).
Suppose, I need to retrieve a file and write it to stream. But how can I create the java.io.File
object without knowing file extension(images can be jpg, png and so on)? Now in my database there are only images with .png extension and I do this:
File file = new File(pathToAvatarFolder + File.separator + user.getId() + ".png");
Is there an elegant solution for this? Only brute force solution comes to my mind:
List<String> imageExtensions = new ArrayList<>();
imageExtensions.add(".png");
imageExtensions.add(".jpg");
imageExtensions.add(".jpeg");
File file;
for(int i = 0; i < imageExtensions.size(); i++) {
file = new File(pathToAvatarFolder + File.separator + user.getId() + imageExtensions.get(i));
if (file.exists()) {
break;
}
file = null;
}
Just to be clear, I need to instance java.io.File
object using pathname without extension.
Upvotes: 1
Views: 1102
Reputation: 326
import java.nio.*;
import java.nio.file.*;
Files.probeContentType((new File("filename.ext")).toPath());
This returns the type of the files. For png, it will be image/png.
Upvotes: 1