问题:我无法用空格解析我的文件test.txt。我可以1)读取文本文件,并且我可以2)解析字符串,但是我无法连接这两个文件并解析文本文件!我的目的是学习如何分析文本文件。这是一个简化的方法。合并读取和解析文本text.txt
进度:到目前为止,我可以使用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());
}
}
抢占感谢您的分享你的知识。阅读和解析的许多帖子都已经在这里解决了,但我没有理解实现他人的解决方案。请原谅,我只是在几个月的时间里一直在学习Java,并仍然在与基础知识斗争。
你能解释一下你试图实现的内容吗? – root
嘿根,我已经添加了文本文件内容(只是简单的占位符文本),并描述了我的目的。我想让文本文档中的每个单词用行分隔。 – PizzaAndCode