【问题标题】:How to use substrings to extract text from buffered reader如何使用子字符串从缓冲阅读器中提取文本
【发布时间】:2013-01-03 22:54:50
【问题描述】:

我正在尝试使用 substrings 和 bufferedreader 提取两个标签之间的文本,但出现 indexoutofbounds 异常。使用 if 语句是因为我正在解析 5 个网页,并且我想从每个网页中读取文本,下面是我的代码:

    public static List<WebPage> readRawTextFile(Context ctx, int resId) {
    InputStream inputStream = ctx.getResources().openRawResource(
            R.raw.pages);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    StringBuilder text = new StringBuilder();
    String txt1 = text.toString();
    try {
        int count = 0;
        while ((line = buffreader.readLine()) != null) {

            if (line.length() == 0) {
                int sURL = line.indexOf("<!--");
                int eURL = line.indexOf("-->");
                String newSub = txt1.substring(txt1.indexOf(sURL) + 1,
                        txt1.indexOf("\""));
                System.out.println(newSub);
            }

【问题讨论】:

  • 好吧,对于初学者,您可能想要line.length() != 0 而不是line.length() == 0,对吧?
  • 我想使用 line.length()=0,所以我可以用空格分隔第一页,然后在继续之前从第一页读取文本
  • 也许你“想要”,但这不是代码告诉 JVM 要做的事情。

标签: java android bufferedreader substring


【解决方案1】:

看看这段代码:

if (line.length() == 0) {
    int sURL = line.indexOf("<!--");
    int eURL = line.indexOf("-->");
    String newSub = txt1.substring(txt1.indexOf(sURL) + 1,
            txt1.indexOf("\""));
    ...
}

如果该行为空,您将进入区块。所以sURLeURL 肯定是-1。

然后您使用txt1.indexOf(-1),这很奇怪(为什么要使用indexOf 并传入索引?) - 我强烈怀疑这里的indexOf 值都将是-1,所以你将拥有:

String newSub = txt1.substring(0, -1);

...这将失败。也不清楚你为什么在这里使用txt1.substring 而不是line.substring

基本上,我认为您的代码存在一堆错误。您应该非常仔细查看每一行,然后更改它,直到它真正有意义为止。然后添加单元测试...

【讨论】:

    【解决方案2】:

    因为sURL已经是

    int sURL = txt1.indexOf("<!--");
    

    ,那么txt1.indexOf(sURL)

    中没有多大意义
    String newSub = txt1.substring(txt1.indexOf(sURL) + 1, txt1.indexOf("\""));
    

    行,可能你的意思是这样的:

    String newSub = txt1.substring(sURL + 1, txt1.indexOf("\""));
    

    这只会留下您为什么稍后使用txt1.indexOf("\"") 的谜团。

    【讨论】:

      猜你喜欢
      • 2015-08-30
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多