watchmerisxe watchmerisxe - 1 month ago 7
Java Question

Java does not release the process after writing inputstream to file

I am building a java RestService and try to upload an Image from the frontend and try to save it somewhere on my computer. The Problem is that I only can open the uploaded image after I closed the server. When I try to open the image while the server is still running, I just get a black image...

This is my code:

private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {

try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];

out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {

e.printStackTrace();
}

}


That is the code where I call writeToFile()...

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {


String uploadedFileLocation = "c://Users/leona/Desktop/EOT/src/main/Backend_EOT/sparti-meetme-63dfc731c375/meetmeserver/src/main/webapp/" + name;

// save it
writeToFile(uploadedInputStream, uploadedFileLocation);

String output = "File uploaded to : " + uploadedFileLocation;

try {
uploadedInputStream.close();
}catch (Exception e) {
log.debug("Input Stream konnte nicht geschlossen werden");
}

return Response.status(200).entity(output).build();

}


I really would appreciate if someone could help me with that.

Answer

You're opening 2 FileOutputStreams but only closing one of them. here is a snippet of your code with a comment added by me, showing which line to delete:

try {
    OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
    int read = 0;
    byte[] bytes = new byte[1024];

    // delete the following line, you already opened the output stream right after the `try`.
    out = new FileOutputStream(new File(uploadedFileLocation));

As an aside, make sure you close the uploadedInputStream. It's not being closed in the code you posted. The best practice would be to close it in the same scope you create it in, which in this case would be outside of the function you posted.

Update:

Now that we see more of the code, we see that you're being passed an InputStream by a framework. Let the framework handle closing it. As mentioned above, the best practice is to close streams in the scope they are created in. In this case, that would be the Jersey framework.