2016-05-15 89 views
-4

我看到這類問題已被問到,但他們似乎沒有回答我的問題。 :(Java 8 - 如何在java中逐行讀取文件?

我有一個文本文件 「file.txt」,但其內容是這樣的

ABCD
EFGH
IJKL

現在我想的是,不同類型的線通過不同的字符串變量存儲在我的程序中
例如

String firstLine , String secondLine , ThiredLine; 

,當我打印上述字符串然後輸出將是

firstLine :: abcd & secondLine :: efgh & thiredLine :: ijkl 

是有可能使用的readLine()方法或任何其他做呢?

在此先感謝 :)

+0

所以文件只有三行?我不認爲有許多變量作爲線是解決任何問題的好方法。你想用這些變量做什麼? –

+0

這是「存儲玩家在板球運行」11人的一部分; 11行;和11個變量;) – Manish

+1

*「可以使用'readLine()'方法嗎?」*是的。 – Andreas

回答

0

你要去了解的做法似乎有點粗。還有很多其他方法可以做到這一點。許多其他人已經提交了答案,但是這裏有一個替代方案。

另請注意,從Java 7開始,現在有用於實現AutoCloseable接口的類的自動資源管理。

就這樣說,這是一種做法。

String[] lines = new String[11]; //11 players 
    try (BufferedReader reader = new BufferedReader(new FileReader("file path here"))) { 
     String line = null; 
     int index = 0; 
     while ((line = reader.readLine()) != null) { 
      lines[index++] = line; 
     } 
    } catch (IOException e) { 
     System.out.println(e.getMessage()); 
    } 
2

如果你真的想這樣做的,你可以寫你這樣的代碼:

Scanner sc = new Scanner("file.txt"); 
String firstLine = sc.nextLine(); 
String secondLine = sc.nextLine(); 
String thirdLine = sc.nextLine(); 

然而,這將是使用更方便陣列和一個for循環:

Scanner sc = new Scanner("file.txt"); 
String[] lines = new String[3]; 
for (int i=0; i<lines.length; i++) { 
    lines[i] = sc.nextLine(); 
} 

或者,你可以使用一個ArrayListwhile循環。以這種方式做的好處是,這段代碼無論工作文件中的行數:

Scanner sc = new Scanner("file.txt"); 
ArrayList<Sting> lines = new ArrayList<>(); 
while (sc.hasNextLine()) { 
    lines.add(sc.nextLine()); 
} 
1

你可以參考java.nio.file.Path和的Java API的java.nio.file.Files類。
你可以得到關於這個問題的答案。
第一步應該通過文件路徑獲取Path對象。
第二步可以通過Files.readAllLines(Path path)方法逐行讀取內容。 在下面的例子:

Path path = FileSystems.getDefault().getPath(filePath); 
    List<String> datas = Files.readAllLines(path)