我正在尝试从 URL 下载文件。我有以下代码。
package com.example.downloadfile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadFile extends Activity {
private static String fileName = "al.jpg";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("This is download file program... ");
try {
//this is the file you want to download from the remote server
String path ="http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg";
//this is the name of the local file you will create
String targetFileName = "al.jpg";
boolean eof = false;
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH_op = Environment.getExternalStorageDirectory() + "/download/" + targetFileName;
tv.append("\nPath > " + PATH_op);
FileOutputStream f = new FileOutputStream(new File(PATH_op));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
tv.append("\nAnother append!");
this.setContentView(tv);
}
}
谁能告诉我这段代码有什么问题。我看不到应该下载的文件。我是 java 和 android 开发的新手,非常感谢您的帮助。 :)
最佳答案
您正在主应用程序线程上执行网络 I/O。充其量,这会在下载进行时卡住您的 UI。在最坏的情况下,您的 Activity 会崩溃并显示“应用程序无响应”(ANR) 对话框。
您正在尝试写入外部存储上可能不存在的目录 (
download/
)。请先创建目录。请考虑改用
Log.e()
进行错误记录,因为我不知道printStackTrace()
是否适用于 Android。
此外,请确保您拥有 WRITE_EXTERNAL_STORAGE
权限,并且您正在使用 adb logcat
、DDMS 或 Eclipse 中的 DDMS 透视图来检查 LogCat 并查找您尝试记录的错误消息。
关于java - Android:如何在android中下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5881774/