【发布时间】:2011-05-03 08:52:35
【问题描述】:
我想从互联网上下载一个文件。到目前为止,我有 ff。代码:
package com.example.downloadfile;
import java.io.BufferedOutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class DownloadFile extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
String url = "http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg";
String FileName = "/LocalDisk/jm"; // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}catch (Exception e){
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
this.setContentView(tv);
}
}
我遇到了一个错误,当我运行此代码时,我的 UI 中出现了“Error: /LocalDisk/jm”。
非常感谢您的帮助!我是 java 和 android 开发新手... :)
【问题讨论】:
-
处理异常时,
message不一定是最重要的部分。至少同样重要的是异常类型和堆栈跟踪。请尝试e.printStackTrace()以获取有关该问题的更多详细信息。 -
还有:
.close()刷新流,之前不需要调用flush()。关闭bout也会关闭fos。