This is the code I am using to download a file from a URL. How can I optimize this code, or is there another way to download a file faster? And how much should the value of the BUFFER_SIZE
be?
private final int BUFFER_SIZE = 4096; public String downloadFile(String fileURL, String saveDir) throws IOException { URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); } InputStream inputStream = httpConn.getInputStream(); String saveFilePath = saveDir + File.separator + fileName; FileOutputStream outputStream = new FileOutputStream(saveFilePath); int bytesRead = -1; byte[] buffer = new byte[BUFFER_SIZE]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); return saveFilePath; } httpConn.disconnect(); return null; }