2015-09-27 59 views
1

我有這個問題,我有20個文本文件,名稱幾乎相同,但文本不同(其中有int &雙值)。這些名稱是這樣的:在java中使用不同的名字讀取多個文本文件

  • fake_weather_riyadh_1
  • fake_weather_riyadh_2
  • fake_weather_riyadh_3

等等,直到其達到20

所以我的問題是,哪一種方法,我需要爲了使用,使程序讀取 所有這些文件的內容,而無需編寫:

String inputFileName = "fake_weather_riyadh_1.txt"; 
String inputFileName = "fake_weather_riyadh_2.txt"; 

注:我我仍然是Java的初學者。

我希望我很清楚,謝謝。

+3

你嘗試過什麼到目前爲止? – QuakeCore

+0

@John看看我的解決方案,如果你有更多疑問,請在評論中告訴我。 – user3437460

回答

0

您可以把所有這些文件的目錄,然後列出目錄的內容,就像這樣:

File directory = new File("directory/path"); 
File[] listOfFiles = directory.listFiles(); 

for (File file : listOfFiles) { 
    // Access file.getName() or do anything else here 
} 

或者,如果你只是提前知道文件名,並希望只讀這些特定的文件,假設它們在你的問題中被編號,你使用for循環。

for (int i = 1; i <= 20; i++) { 
    String filename = "fake_weather_riyadh_" + i + ".txt" 
    // Read file content here 
} 

希望它有幫助。

+0

非常感謝你,確實有幫助:D – John

0

一種可能的方法是將這些文件放到特定的目錄中。然後你可以通過fs操作列出文件並將它們存儲在一個數組中。之後,你可以遍歷它們。

+0

非常感謝你 – John

0

你可以這樣做:

//Scan through the files in the directory 

if (filename.startsWith("fake_weather_riyadh")) //where filename is a String 
    //read this file 
+0

非常感謝你,我感謝你的努力 – John