我正在嘗試使用Class In(http://introcs.cs.princeton.edu/java/stdlib/javadoc/)來讀取文件,而我沒有收到任何迴應。我的代碼目前是:Java:文件閱讀與類中。爲什麼沒有輸出?
public class TestingIn {
public static void main(String [] args){
In file = new In("textfile.txt");
while (!file.isEmpty()) {
String str = file.readAll();
System.out.println(str.substring(0, 100));
System.out.println("abc: testing the file");
}
System.out.println("123: testing compilation");
}
}
打算打印兩個測試字符串和文件textfile.txt的前100個字符。代碼編譯正常並打印出測試字符串「123:測試編譯」,但它不打印出字符串「abc:測試文件」或文件的前100個字符(如果這樣會產生任何影響,則爲http://www.gutenberg.org/files/39063/39063-0.txt )。
我正在使用eclipse,並將textfile.txt放置在我的項目頂層。到目前爲止我嘗試過的東西包括查看上面鏈接的API,谷歌搜索(這是因爲單詞In is common有點棘手),搜索stackoverflow,搜索文件輸入方法(主要是掃描儀),更改我的代碼爲:
while (!file.isEmpty()) {
String line = file.readLine();
if (line.contains("mountain"))
System.out.println(line);
}
當然,將其關閉並再次打開。感謝您抽出時間來閱讀。
您正在'In'類的構造函數中指定文件名,而不是路徑。 Java文檔沒有提到從哪裏獲取文件。有一個方法'exists()';你可以打電話,並檢查文件是否正在加載。 – Kshitij 2013-03-24 10:42:56
System.out.println(file.exists());返回true – user2172005 2013-03-24 11:01:21
另一種方式來讀取整個文件作爲一個字符串,沒有第三方庫:'String str = new String(Files.readAllBytes(Paths.get(「textfile.txt」)),StandardCharsets.UTF_8);' – VGR 2013-03-24 11:29:38