下载文本的类和方法
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownload {
//下载文本文件
public String download(String strurl){
StringBuffer sb=new StringBuffer();
String line=null;
BufferedReader buffer=null;
try{
URL url=new URL(strurl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
buffer=new BufferedReader(new InputStreamReader((conn.getInputStream()),"UTF-8"));
while((line=buffer.readLine())!=null){
sb.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
buffer.close();
}catch(Exception e){
e.printStackTrace();
}
}
return sb.toString();
}
}
在Activity中调用
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.zhu.util.*;
public class Mp8Activity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mp8);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.layout.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if(item.getItemId()==R.id.about){
//关于
}else if(item.getItemId()==R.id.update){
//更新文件列表
String xml=downloader("http://127.0.0.1:8080/MP3/resurce.xml");
System.out.println("xml-->"+xml);
}
return super.onOptionsItemSelected(item);
}
private String downloader(String strurl){
HttpDownload http=new HttpDownload();
String result=http.download(strurl);
return result;
}
}
测试一下得到的结果是
xml-->
无法将文件中的内容输出出来