code_junkie

Java http download corrupts file

Nov 13th, 2011
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. private void downloadJar(String fileName, long crc32Server) throws IOException {
  2. System.out.println("Downloading file '" + fileName + "' from server '" + mServer + "'.");
  3. HttpURLConnection sourceConnection = null;
  4. BufferedInputStream inputStream = null;
  5. BufferedWriter fileWriter = null;
  6. long crc32Client;
  7. try {
  8. URL sourceURL = new URL(fileName);
  9. try {
  10. sourceConnection = (HttpURLConnection)sourceURL.openConnection();
  11. }
  12. catch (MalformedURLException exc) {
  13. throw new RuntimeException("Configured URL caused a MalformedURLException: ", exc);
  14. }
  15. sourceConnection.setRequestProperty("Accept-Encoding", "zip, jar");
  16. sourceConnection.connect();
  17. inputStream = new BufferedInputStream(sourceConnection.getInputStream());
  18. fileWriter = new BufferedWriter(new FileWriter(targetFolder + File.separator + fileName));
  19. CRC32 crc32 = new CRC32();
  20. for (int singleByte = inputStream.read(); singleByte != -1; singleByte = inputStream.read()) {
  21. fileWriter.write(singleByte);
  22. crc32.update(singleByte);
  23. }
  24. crc32Client = crc32.getValue();
  25. }
  26. finally {
  27. if (inputStream != null) {
  28. inputStream.close();
  29. }
  30. if (fileWriter != null) {
  31. fileWriter.flush();
  32. fileWriter.close();
  33. }
  34. if (sourceConnection != null) {
  35. sourceConnection.disconnect();
  36. }
  37. }
  38. if (crc32Client != crc32Server) {
  39. // deleteFile(fileName);
  40. throw new IOException("CRC32 did not match for file '" + fileName + "': " + crc32Client + "!="
  41. + crc32Server);
  42. }
  43. }
Add Comment
Please, Sign In to add comment