I need a faster way to download a textfile from a url in Java. For a file of about 2400 lines, the code takes approximately 2 mins (132 seconds). The problem is that I need an update every minute, which is silly if the processing takes over 2 minutes.
This is what I have tried so far:
public void readFileOnline() throws Exception{
Long now = new Date().getTime();
URL oracle = new URL("myurl");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String currentline;
while ((currentline = in.readLine()) != null){
// Location location = gson.fromJson(currentline, Location.class);
// locations.put(location.getTime(), location);
locations.add(currentline);
}
in.close();
Long done = new Date().getTime();
System.out.println("TOTAL TIME " + (done-now));
}
As you can see, there is some line processing needed. So I tried commenting the processing of the lines out and just save the lines in a collection, but seems to be no real speed optimisation there.
I also tried to just download the file and store it as a temporary file:
public String downloadAsTemp() throws Exception{
Long now = new Date().getTime();
String url = "myurl";
URLConnection request = null;
request = new URL(url).openConnection();
InputStream in = request.getInputStream();
File downloadedFile = File.createTempFile("temp", "end-of-file");
FileOutputStream out = new FileOutputStream(downloadedFile);
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer);
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
in.close();
out.close();
Long done = new Date().getTime();
System.out.println("TOTAL TIME " + (done-now));
return downloadedFile.getAbsolutePath();
}
It gives the same result (approximately 2 mins). I started using retrofit 2 to download the file. Unfortunately, during my search I lost my temper and deleted the code. Overall, you can say that even with Retrofit, it took too long. The file size is about 50MB, the lines of the file tend to get quite long.
I also stumbled upon this but the post dates from 2011, surely there are newer, faster ways? Also, the FileUtils link is dead :-).
So basically, I need to be able to download and process a 50MB file from a server under 1 min and the above is not working. Thanks!