我的Android应用程序有一个要求。我需要下载和保存文件在特定文件夹的SD卡编程。我已经开发了源代码,它是
String DownloadUrl = "http://myexample.com/android/";
String fileName = "myclock_db.db";
DownloadDatabase(DownloadUrl,fileName);
// and the method is
public void DownloadDatabase(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://myexample.com/android/");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
uconn.setReadTimeout(TIMEOUT_CONNECTION);
uconn.setConnectTimeout(TIMEOUT_SOCKET);
InputStream is = uconn.getInputStream();
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
int dotindex = fileName.lastIndexOf('.');
if(dotindex>=0){
fileName = fileName.substring(0,dotindex);
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
}
}
现在的问题是只有文件名为myclock_db.db的空文件保存在路径中。但我需要下载并保存文件的内容在特定的文件夹。
您的下载URL不是任何文件的链接。这是一个目录。确保它是一个文件并且存在。还要检查logcat窗口中的错误日志。还有一个建议,在catch块中执行printStackTrace()总是比在log中执行printStackTrace()更好。它给出了一个更详细的错误视图。
改变这一行:
URL url = new URL("http://myexample.com/android/");
:
URL url = new URL("http://myexample.com/android/yourfilename.txt"); //some file url
接下来,在catch块中添加以下行:
e.printStackTrace();
同样在目录路径中,应该是这样的:
File dir = new File(root.getAbsolutePath() + "/mnt/sdcard/myclock/databases");
代替
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
接下来,确保你已经获得了Android manifest中写入外部存储的权限。