使用stringbuilder和bufferedreader来读取多个链接

时间:2013-11-29 08:14:24

标签: java android bufferedreader stringbuilder delimiter

我正在尝试从下面的代码中的xml源txt文件中读取多个rss链接。我使用;作为分隔符。从调试开始,它似乎将所有链接发送到RSS_LINK,这显然不起作用。

StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;

try {
    while ((line = br.readLine()) != null) 
    {
       rsslink.append(line) ;
    }
    String [] arr = rsslink.toString().split(";"); 
    for (int i = 0; i < arr.length; i++)
        {
        }
} 
catch (IOException e) 
{
    e.printStackTrace();
}
String RSS_LINK = rsslink.toString();

Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try 
{
    XMLRssParser parser = new XMLRssParser();
    rssItems = parser.parse(getInputStream(RSS_LINK));
} 
catch (XmlPullParserException e) 
{
    Log.w(e.getMessage(), e);
} 
catch (IOException e) 
{
    Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}

新代码

protected void onHandleIntent(Intent intent) 
{   
    StringBuilder rsslink = new StringBuilder();
    InputStream is = getResources().openRawResource(R.raw.xmlsource);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;

    try {
        while ((line = br.readLine()) != null) 
        {
           rsslink.append(line) ;
        }
        String [] arr = rsslink.toString().split(";"); 
        for (int i = 0; i < arr.length; i++)
        {
            String RssLink = arr[i];

            Log.d(Constants.TAG, "Service started");
            List<RssItem> rssItems = null;
            try 
            {
                XMLRssParser parser = new XMLRssParser();
                rssItems = parser.parse(getInputStream(RssLink));
            } 
            catch (XmlPullParserException e) 
            {
                Log.w(e.getMessage(), e);
            } 
            catch (IOException e) 
            {
                Log.w(e.getMessage(), e);
            }
            Bundle bundle = new Bundle();
            bundle.putSerializable(ITEMS, (Serializable) rssItems);
            ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
            receiver.send(0, bundle);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:1)

您拆分了rsslink,但不是使用生成的arr,而是继续使用仍然包含所有链接且rsslink合并的;

您需要将所有rss处理(解析等)放入循环中:

String [] arr = rsslink.toString().split(";"); 
for (int i = 0; i < arr.length; i++)
    {
        // HERE IS THE PLACE TO HANDLE a single RSS Link. arr contains the single link
    }