java - 结合读取和解析 text.txt

标签 java parsing

问题:我无法按空格解析文件 test.txt。我可以 1) 读取文本文件,我可以 2) 解析字符串,但我无法连接两者并解析文本文件!我的目的是学习如何分析文本文件。这是一种简化的方法。

进展:到目前为止,我可以使用 FileReader 和 BufferedReader 读取 test.txt,并将其打印到控制台。此外,我可以解析简单的字符串变量。个别操作运行,但我正在努力解析实际的文本文件。我相信这是因为我的 test.txt 存储在缓冲区中,并且在我 .close() 之后,我无法打印它。

文本文件内容: 这是一个 仅创建文本文件 用于测试目的。

代码:

import java.io.*;

public class ReadFile {

    //create method to split text file, call this from main
    public void splitIt(String toTest)
    {
        String[] result = toTest.split(" ");

        for (String piece:result)
        {
            //loop through the array and print each piece
            System.out.print(piece);
        }
    }


    public static void main(String[] args) {

        //create readfile method    
        try
        {
            File test = new File("C:\\final\\test.txt");
            FileReader fileReader = new FileReader(test);
            BufferedReader reader = new BufferedReader(fileReader);

            String line = null;

            //While there are still lines to be read, read and print them
            while((line = reader.readLine()) != null)
            {
                System.out.println(line);
                splitIt(line);
            }

            reader.close();
        }

        //Catch those errors!
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

//      readFileMethod a = new readFileMethod(line);
        System.out.println(a.splitIt());

    }

}

先发制人,感谢您分享您的知识。许多关于阅读和解析的帖子已经在 SO 上解决了,但我不了解如何实现其他人的解决方案。请原谅,我只学习了几个月的 Java,但仍然难以掌握基础知识。

最佳答案

好吧,让我们把拆分成一个方法

private static void splitIt (String toTest) {

  String[] result = toTest.split(" ");

  for (String piece:result)
  {
      //loop through the array and print each piece.
      System.out.println(piece);
  }
}

然后你可以从内部调用它

    while((line = reader.readLine()) != null)
    {
        System.out.println(line);
        splitIt (line);
    }

关于java - 结合读取和解析 text.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40732993/

相关文章:

regex - sed:更改 .yml 文件中环境属性的值

c++ - 尝试解析保存为std::string的大文本文件

java - 为什么selenium只点击第一行代码而不点击其他两行?

java - log4j2使用CsvParameterLayout,如何在单元格中添加时间戳?

java - 需要空格

java - 检查嵌套循环中的缓冲区

ios - 如何将xml解析成表格 View

c# - 从完全限定的方法名称中拆分参数

java - 如何解析名称=值^^名称=值^^名称=值

java - DynamoDB 用户管理的用户组