0

I have a java application which uses spring rest to upload a jar file.
But the uploaded file is corrupted and I am not able to access the jar file from the server.
Please help.

fileloc = fileloc.replace("$", "/");
String filename = uploadedFileRef.getOriginalFilename();
String path = fileloc + filename;
byte[] buffer = new byte[1000];
File outputFile = new File(path);
FileInputStream reader = null;
FileOutputStream writer = null;
int totalBytes = 0;
try {
  outputFile.createNewFile();
  reader = (FileInputStream) uploadedFileRef.getInputStream();
  writer = new FileOutputStream(outputFile);
  int bytesRead = 0;
  while ((bytesRead = reader.read(buffer)) != -1) {
    writer.write(buffer);
    totalBytes += bytesRead;
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try {
    reader.close();
    writer.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
}
F0XS
  • 1,271
  • 3
  • 15
  • 19
Pavan Jois
  • 31
  • 5

1 Answers1

0

You call

writer.write(buffer);

so you write always the buffer size. Imagine the last read reads 10 bytes only but you will write 1000 bytes anyway.

Use

write(buffer, 0, bytesRead );

Or just check the question

StanislavL
  • 56,971
  • 9
  • 68
  • 98