[英]How to download a dat file from a weblink into a path in SDcard in my Android app?
在应用程序即时开发中,我必须从网络服务器链接下载一个dat文件和一个xml文件。 下载xml没有问题但是在下载dat文件时它会抛出异常。我怎么能过来这个状态。谢谢你们..
例外
02-01 16:33:34.713: W/System.err(1404): java.io.FileNotFoundException: http://www.myingage.com/bkpdrctry/dontwo.dat
02-01 16:33:34.723: W/System.err(1404): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1162)
实际代码如下
protected static void downloadFile(String stringUrl, String path){
try {
URL url = new URL(stringUrl);
DebugLog.LOGD("URL " +url );
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,path);
DebugLog.LOGD("download to sd card " +url );
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
DebugLog.LOGD("File written successfully in " +path );
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
上面的函数在这里调用:
downloadFile("http://www.myingage.com/bkpdrctry/dontwo.xml","/Test/dontwo.xml");
downloadFile("http://www.myingage.com/bkpdrctry/dontwo.dat","/Test/dontwo.dat");
在浏览器上打开http://www.myingage.com/bkpdrctry/dontwo.dat
。
抛出HTTP 404
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.