Search code examples
spring-bootmultipartform-datamultipart

Why isEmpty () not null checked?


First, ask for your understanding that English is not fluent.

I am currently implementing an upload function using MultipartFile. It is checking for an empty value with isEmpty() in case there is no file. When i submit without selecting a file, a NullPointerException occurs in the isEmpty () part.

So, when i do not have a file, it works fine if i check file != null instead of isEmpty(). Looking at the implementation of MultipartFile(ex:CommonsMultipartFile, StandardMultipartFile...), this only check if the file size is zero. If so, I wonder if it is OK to check it like file != null to check for null.

if(uploadFile.isEmpty()){ //Here a NullPointerException is thrown
    ...
}

if(uploadFile != null){ //Does not occur here
    ...
}

Solution

  • If uploadFile object is itself null then it means you are calling isEmpty() on a null which throws the NPE

    You can combine the condition like

    uploadFile != null && !uploadFile.isEmpty()