从远程文件读取字符串 - Java

时间:2013-12-01 15:43:49

标签: java string download

我想从我的服务器上读取我的程序的待办事项列表。 我尝试过使用BufferedReaderInputStream,但还没有完全掌握它。

网址为:http://team-m4gkbeatz.eu/Beatsleigher/UniversalAndroidToolkit/UAT.todo

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这是我创建的函数,它使用从url.openStream()获得的 InputStream 。它将页面作为String返回。您可以在之后处理该页面。

public String getpage(URL url)
    {
        try {
            // try opening the URL
            URLConnection urlConnection = url.openConnection();                        
            urlConnection.setAllowUserInteraction(false);

            InputStream urlStream = url.openStream();            
            byte buffer[] = new byte[1000];
            int numRead = urlStream.read(buffer);
            String content = new String(buffer, 0, numRead);

            while ((numRead != -1) && (content.length() < MAX_PAGE_SIZE)) {
                numRead = urlStream.read(buffer);
                if (numRead != -1) {
                    String newContent = new String(buffer, 0, numRead);
                    content += newContent;
                }
            }
            return content;
        } catch (IOException e) {            
            e.printTrackStace();
        }catch(IndexOutOfBoundsException e1){            
            e1.printTrackStace();
        }
    }

使用以下方法调用此函数:

getpage(new URL("http://team-m4gkbeatz.eu/Beatsleigher/UniversalAndroidToolkit/UAT.todo"));