I'm rather new to all this, so please forgive me. I'm trying to download an XML file to the device, which can then be parsed. The code I have at the moment is -
public class DownloadFromURL implements Runnable {
private static final int BUFFER_SIZE = 4096;
@Override
public void run() {
Log.i("Download From URL", "Run");
String fileURL = "http://m.highways.gov.uk/feeds/rss/AllEvents.xml";
String saveDir = "/data/data/com.androidandyuk/files";
URL url;
try {
url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection)
url.openConnection();
int responseCode = httpConn.getResponseCode();
Log.i("Download from URL", "Resp Code :" + responseCode);
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
Log.i("Download from URL", "Opening a Stream");
// opens an output stream to save into file
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();
Log.i("Download", "File downloaded");
} else {
Log.i("Download", "No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Which is then run by -
DownloadFromURL getTraffic = new DownloadFromURL();
Thread t = new Thread(getTraffic);
t.start();
But as it runs, I get an error saying 'java.io.FileNotFoundException: /data/data/com.androidandyuk/files/AllEvents.xml (No such file or directory)'
Can anyone please help?
(And if you want to downvote me, please at least comment why, as I get downvoted even when I feel I've formatted my question well... and done lots of searching for the answer already! Thanks)