java - 如何使用子字符串从 bufferedreader 中提取文本

标签 java android bufferedreader substring

我正在尝试使用子字符串和 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);
            }

最佳答案

看看这段代码:

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

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

然后您使用 txt1.indexOf(-1),这从一开始就很奇怪(为什么要使用 indexOf 并传入索引?) -我强烈怀疑这里的两个 indexOf 值都将是 -1,所以你会得到:

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

...这将会失败。根本不清楚为什么您在这里使用 txt1.substring 而不是 line.substring

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

关于java - 如何使用子字符串从 bufferedreader 中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14148599/

相关文章:

java - 如何在 Else 条件下动态访问在 if 条件下创建的 ArrayList?

java - 需要重启tomcat以进行html更改

java - map android v2 -clear() 方法的问题

java - 套接字 : cannot read from BufferedReader and/or write to PrintWriter in certain conditions

java - 如何为 RabbitMQ DefaultConsumer 设置超时?

java - 通过 $chosen 变量在运行命令中自动调用 Java 参数

android - 如何在 ListView 中滚动时保存 CheckBox 的状态?

java - 使matlab代码与android兼容

java - 套接字关闭异常

java - BufferedReader 使用 .read() 方法实际读取了多少字节?