【问题标题】:How to read a specific line in a text file and return a part of it?如何读取文本文件中的特定行并返回其中的一部分?
【发布时间】:2014-04-30 00:00:28
【问题描述】:

我在一个文件中有几个字符串,我应该停止并从这些字符串中读取值。例如:

This is the first line
#1 stop = 300
This is the third line
This is the 4th line
#2 stop = 400
This is the 6th line

我需要停在 #1 并从那里提取值 300。然后我必须停在 #2 并提取 400,依此类推。

我对 Java 非常陌生,无法弄清楚我的代码有什么问题。 (我还没有提取值):

public static void main(String[] args) throws IOException { 
        //read
        File fromFile = new File("in.txt");         
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fromFile));
        String line;
        String firstHandler="";
        while ((line = bufferedReader.readLine()) != null) { 
            bufferedReader.readLine();       
            if (firstHandler.startsWith("#1")){
                System.out.println(firstHandler);
                String[] parts = firstHandler.split("=");   
                System.out.println(Arrays.toString(parts));  
             } 
                 break;
        }

        System.out.println(line);
         bufferedReader.close();
    }
}

此时它只打印第一行,这根本不是我需要的。谁能向我解释这应该如何以正确的方式完成?

【问题讨论】:

  • 您需要进一步概括您的模式。您需要能够在 # 之后查找任何数字,而不是只查找 #1
  • ' if (firstHandler.startsWith("#1")){ ' 看起来不适合您的目的,而是使用分隔符“#”,因此您的代码应如下所示 ' if (firstHandler.startsWith(" #")){ '
  • 打开文件时没有指定编码

标签: java parsing text bufferedreader


【解决方案1】:

错误在这 4 行:

    String firstHandler="";
    while ((line = bufferedReader.readLine()) != null) { 
        bufferedReader.readLine();      
        if (firstHandler.startsWith("#1")){

您从while 语句中读取了一行。对于读取的每一行,您输入块。但是在这个块中,你又读到了另一行。

然后,你和"#1"比较的不是你刚刚读到的那一行,而是firstHandler,它被初始化为空字符串一次,从未修改过。代码应该是:

    while ((line = bufferedReader.readLine()) != null) { 
        if (line.startsWith("#1")) {

reader 也应该在 finally 块中关闭,但这是另一回事。

【讨论】:

  • 太棒了...您的解释有一段时间了...+1 !! :)
  • 我认为分隔符也有问题,它应该是“#”而不是“#1”,因为“#1”只会读取第一行
  • 哦@NoobEditor 知道了 +1 :)
  • @JB Nizet if (line.startsWith("#1")) 有道理,谢谢。但是,它仍然只读取第一行。我怎样才能让它也读取其他行,以便它可以达到#1?
  • 解决了分隔符问题
【解决方案2】:

首先,正如 cmets 中所指出的,您需要匹配以 # 开头的行,因为有多行以 # 开头但具有不同的第二个字符。

接下来,您需要检查正在读取的行的值以检查# 字符。因此,您可以去掉 firstHandler 变量并改用 line 变量。

最后,您需要删除break 语句,因为这会导致循环在第一行之后退出。这就是您只能在屏幕上看到第一行的原因。

因此,您的代码可以更改为以下内容:

while ((line = bufferedReader.readLine()) != null) 
        {                
         if (line.startsWith("#"))
           {
            System.out.println(line);
            String[] parts = line.split("=");   
            System.out.println(Arrays.toString(parts));  
           } 
         }

【讨论】:

  • 谢谢!我是否必须将字符串拆分为数组才能返回“300”值,还是有其他更好的方法?
  • 如果您的行仅以 # 开头并遵循相同的格式,您可能只是在“300”文本出现的索引处获取子字符串。但由于看起来这些行可以从“#1”到#1000 甚至更多,所以最好使用 split 方法。
  • 谢谢你的解释,现在我更清楚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
  • 2021-03-04
相关资源
最近更新 更多