1

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.

2
  • 1
    At the long run store the file extension / mime type too. Your solution probably is faster than doing a directory scan with a file filter. Commented Jan 2, 2018 at 11:02
  • As Joop mentioned save the file extension in your database, too. Or alternatively change the avatar fileext to a fixed value. Anyway I would recommend you to generate a random filename on upload. This prevents a lot of attack scenarios. Commented Jan 2, 2018 at 12:55

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

3 Comments

This won't work. The OP is missing the the concrete path to the file, therefore it's content can't be checked.
"Just to be clear, I need to instance java.io.File object using pathname without extension." @salkisore The OP claims to have the path.
I used this to determine whether the given file is an image or not. if(Files.probeContentType((new File("filename.ext")).toPath()).startsWith("image")) {...} Using this condition, we can later instantiate the File.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.