代码之家  ›  专栏  ›  技术社区  ›  nanachan

如何读取文本文件中的特定行并返回其中的一部分?

  •  1
  • nanachan  · 技术社区  · 12 年前

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

    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();
        }
    }
    

    此时,它只打印第一行,这根本不是我需要的。有人能向我解释一下如何以正确的方式完成这项工作吗?

    2 回复  |  直到 12 年前
        1
  •  3
  •   NoobEditor    12 年前

    错误在以下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 但那是另一回事。

        2
  •  2
  •   shree.pat18    12 年前

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

    接下来,您需要检查正在读取的行的值,以检查#字符。所以,你可以摆脱 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));  
               } 
             }