download - Files downloaded as Binary with Java are corrupted -
i have written downloader should used download text files, images. download files binaries. many of downloads work well, parts of text files , many image files corrupted. errors occur @ same files , @ same places (as long can tell when analysing text files). used code downloading:
public file downloadfile(httpurlconnection connection) { return writefiledatatofile(getfiledata(connection)); } //downloads data of file , returns content string private list<byte> getfiledata(httpurlconnection connection) { list<byte> filedata = new arraylist<>(); try (inputstream input = connection.getinputstream()) { byte[] filechunk = new byte[8*1024]; int bytesread; { bytesread = input.read(filechunk); if (bytesread != -1) { filedata.addall(bytes.aslist(filechunk)); filechunk = new byte[8*1024]; } } while (bytesread != -1); return filedata; } catch (ioexception e) { system.out.println("receiving file @ " + url.tostring() + " failed"); system.exit(1); return null; //shouldn't reached } } //writes data file private file writefiledatatofile(list<byte> filedata) { if (!this.file.exists()) { try { this.file.getparentfile().mkdirs(); this.file.createnewfile(); } catch (ioexception e) { system.out.println("error while creating file @ " + file.getpath()); system.exit(1); } } try (outputstream output = new fileoutputstream(file)) { output.write(bytes.toarray(filedata)); return file; } catch (ioexception e) { system.out.println("error while accessing file @ " + file.getpath()); system.exit(1); return null; } }
i suggest not pass through list of byte, since create list of byte array, array of byte, not efficient.
moreover wrongly assume chunk size (not necesseraly 8192 bytes).
why don't as:
private file writefiledatatofile(httpurlconnection connection) { if (!this.file.exists()) { try { this.file.getparentfile().mkdirs(); //this.file.createnewfile(); // not needed, created @ fileoutputstream } catch (ioexception e) { system.out.println("error while creating file @ " + file.getpath()); //system.exit(1); // instead throw of error or return null throw new yourexception(message); } } outputstream output = null; inputstream input = null; try { output = new fileoutputstream(file): input = connection.getinputstream(); byte[] filechunk = new byte[8*1024]; int bytesread; while ((bytesread = input.read(filechunk )) != -1) { output.write(filechunk , 0, bytesread); } return file; } catch (ioexception e) { system.out.println("receiving file @ " + url.tostring() + " failed"); // system.exit(1); // should avoid such exit // instead throw of error or return null throw new yourexception(message); } { if (input != null) { try { input.close(); } catch (execption e2) {} // ignore } if (output != null) { try { output.close(); } catch (execption e2) {} // ignore } } }
Comments
Post a Comment