[英]Accesing contents of a file in java
我想知道java中是否有任何方法可以訪問計算機中文件的內容。
例如,如果我想制作一個猜詞游戲,我想在其中隨機訪問保存在文件中的單詞。
(我聽說過一種叫做“FileReader”的東西,但不明白如何使用它。)
希望你明白我的意思。
謝謝!!
您可以像這樣讀取 File 的內容。
public void readFile(String fileName){ //Pass file's absolute path
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while((line=reader.readLine())!=null){
System.out.println(line);
}
}
您還可以使用 Files.readAllLines 將整個文本文件作為列表讀取。 你可以這樣做(閱讀和打印):
List<String> sl= Files.readAllLines(Paths.get("test1.txt"));
for (String s:sl) {
System.out.println(s);
}
另一種選擇是像這樣使用 Files.newBufferedReader:
try (BufferedReader br= Files.newBufferedReader(Paths.get("test1.txt")))
{
String line;
while ((line=br.readLine())!=null) System.out.println(line);
}
try(){ } 構造被稱為 try-with-resorces,它在完成時自動關閉打開的文件對象(在本例中為 br)。 它對寫作至關重要,是閱讀的良好編碼習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.