問題:我無法用空格解析我的文件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