![](/img/trans.png)
[英]How do you read a text file, line by line, and separate contents of each line in Java?
[英]Java: How do you read each line of a text file and setting each line as an array element?
我試圖閱讀文本文件的每一行中列出的問題,然后將每一行添加到數組中,以便稍后可以單獨調用它們。 我幾乎肯定可以用Java做,但我不確定如何做到這一點。
我確實弄清楚如何讀取整個文本文件並將其全部設置為字符串:
private static String readFile(String pathname) {
String line = null;
try {
BufferedReader reader = new BufferedReader(new FileReader(pathname));
while((line = reader.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
雖然它與此沒什么關系,但正如我所提到的,這是一個存在問題的文件。 如果我得到這個問題的解決方案,我將有另一個文件來解決問題的所有答案,然后我將為該文件做同樣的事情。
有誰知道一個不太復雜的方法來做到這一點? 如果它必須復雜,那么告訴我。 我想要某種類型的示例,而不僅僅是指向不同站點的鏈接。 我不是說我只會接受這個。
感謝您的時間!
PS我已經閱讀了關於這個主題的其他問題,但找不到合適的答案和/或示例我正在嘗試用Java做什么。
我會使用一個ArrayList ......就像這樣......
ArrayList<String> questions = new ArrayList<String>();
/// in your loop...
while((line = reader.readLine()) != null){
questions.add(line);
}
順便說一句,正如jlordo在注釋中指出的那樣,你構建方法的方式,你的循環的唯一出路是將行變為null,所以,當你到達return語句時,你將返回空值。 你究竟想要回到這里的是什么? 如果它是整個行文件,則需要將它們添加到String中。
而不是數組使用ArrayList
,這是動態的,並找到具體的代碼。
private static List<String> readFile(String pathname) {
String line = null;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(pathname));
while((line = reader.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
對於第二個文件,您應該維護一個map<question,answer>
表示Map<String,String>
。
private static String readFile(String pathname) {
List<String> lines = new ArrayList<String> ();
String line = null;
try {
BufferedReader reader = new BufferedReader(new FileReader(pathname));
while((line = reader.readLine()) != null){
lines.add(line) ;
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
像我一樣使用ArrayList<String>
,它會動態增長。 將它聲明為一個字段,我在這個例子中只使用了一個局部變量。 你可以像以后一樣迭代它:
for(String line : lines)
{
System.out.println(line) ;
}
你不能只是創建一個字符串arraylist並使用readLine()添加讀取的每一行嗎? 然后你可以將arraylist轉換為普通數組。
listArray.toArray(strArray);
這在java 8中非常簡單和簡潔:
List<String> fileLines = Files.lines(Paths.get("/file/path/")).collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.