大神你好,我就是按照这种方法下载文本文件但是就是得不到想要的结果,请求支援一下。

下载文本的类和方法

 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-->
无法将文件中的内容输出出来

String xml=downloader("http://127.0.0.1:8080/MP3/resurce.xml");
你这里为啥能直接调用downloader方法啊??

加点输出试一试:

conn.setDoOutput(true);
conn.getOutputStream().write(("temp=" + System.currentTimeMillis()).getBytes());
conn.getOutputStream().close();

还有,最好在finally把conn也disconnect一下。

试了下,还是没有输出。。。。。