问题:我无法按空格解析文件 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/