从网站下载文本文件

时间:2011-03-01 09:13:22

标签: java android

我已经完成了一个方法来返回托管在网站上的文本文件的字符串值

但是当我调用方法时,我似乎无法获得价值

private String DownloadFromUrl() //this is the downloader method
{  
    String strFileContents = null;
    try 
    {
            String webURL = "http://www.example.net/test/file.txt";
            URL url = new URL(webURL);

            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            //create a byte array
            byte[] contents = new byte[1024];

            int bytesRead=0;

            while( (bytesRead = bis.read(contents)) != -1){

                strFileContents += new String(contents, 0, bytesRead);
            }

       }

    catch (IOException e) 
    {

    }
    return strFileContents;        
}

我从stringreader

中抛出了一个空指针异常
 //Read text from file
    StringBuilder text = new StringBuilder();

    String test = DownloadFromUrl();

    try {
        StringReader sr = new StringReader(test);
        String line="";
        int c,counter =0;
        while ((c = sr.read()) != -1) 
        {
            line+=(char)c;
            counter++;
        }

        char[] singleText = line.toCharArray();

        for (int i = 0; i < counter; i++)
        {
            classifier(singleText[i]);
        }
        text.append(line);

    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }

我测试了我的代码,错误是从带有空指针的stringreader抛出的

但在使用字符串文本进行测试时可正常工作。

所以问题在于DownloadFromUrl方法没有从在线.txt文件中返回文本字符串

添加了错误消息希望这有帮助

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

尝试将InputStream转换为String

public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
  sb.append(line + "\n");
}
is.close();
return sb.toString();

} }

答案 1 :(得分:1)

您需要添加一些日志记录才能找出问题所在。对于两个catch块,请执行以下操作:

catch (IOException e) 
{
    e.printStackTrace();
}

这将帮助您缩小问题的范围。我也会按照@Jignesh Dhua的建议将InputStream转换为String

修改
从您的屏幕截图看,test似乎是null,因此当您尝试创建StringReader时,它会失败并显示NullpointerException。为防止您的应用程序崩溃,您可以在创建null之前检查StringReader

这可以避免崩溃,但不会为您提供数据。在阅读内容之前,我会检查服务器上的response code

int responseCode = urlc.getResponseCode();

我过去也明确使用过HttpUrlConnection,但我不确定它会有多大差异:

/* Open a connection to that URL. */
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();