Fix downloading certain files to a byte array.

This commit is contained in:
Maschell 2018-12-06 15:29:13 +01:00
parent 5603bfb94e
commit e046031dd2

View File

@ -16,6 +16,7 @@
****************************************************************************/ ****************************************************************************/
package de.mas.wiiu.jnus.utils.download; package de.mas.wiiu.jnus.utils.download;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
@ -33,31 +34,29 @@ public abstract class Downloader {
public static byte[] downloadFileToByteArray(String fileURL) throws IOException { public static byte[] downloadFileToByteArray(String fileURL) throws IOException {
int BUFFER_SIZE = 0x800; int BUFFER_SIZE = 0x800;
URL url = new URL(fileURL); URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("User-Agent", Settings.USER_AGENT); httpConn.setRequestProperty("User-Agent", Settings.USER_AGENT);
int responseCode = httpConn.getResponseCode(); int responseCode = httpConn.getResponseCode();
byte[] file = null; ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
if (responseCode == HttpURLConnection.HTTP_OK) { if (responseCode == HttpURLConnection.HTTP_OK) {
int contentLength = httpConn.getContentLength();
file = new byte[contentLength];
InputStream inputStream = httpConn.getInputStream(); InputStream inputStream = httpConn.getInputStream();
int bytesRead = -1; int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE]; byte[] buffer = new byte[BUFFER_SIZE];
int filePostion = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) { while ((bytesRead = inputStream.read(buffer)) != -1) {
System.arraycopy(buffer, 0, file, filePostion, bytesRead); byteArray.write(buffer, 0, bytesRead);
filePostion += bytesRead;
} }
inputStream.close(); inputStream.close();
} else { } else {
log.info("File not found: " + fileURL); log.fine("File not found: " + fileURL);
} }
httpConn.disconnect(); httpConn.disconnect();
return file; byte[] result = byteArray.toByteArray();
byteArray.close();
return result;
} }
} }