[英]Unable to open file in JAVA
我正在嘗試使用BufferedReader在JAVA中打開文件,但無法打開該文件。 這是我的代碼
public static void main(String[] args) {
try
{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((reader.readLine()!= null))
{
line = reader.readLine();
System.out.println(line);
}
reader.close();
}
catch(Exception ex)
{
System.out.println("Unable to open file ");
}
}
出現異常並顯示“無法打開文件”。 為什么我看不懂任何建議。
如果您想變得更現代,請嘗試從Paths
Javadoc中獲取的Java 7解決方案:
final Path path = FileSystems.getDefault().getPath("test.txt"); // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} // No need for catch; let IOExceptions bubble up.
// No need for finally; try-with-resources auto-closes.
您需要將main
聲明為throwing IOException
,但這沒關系。 無論如何,您沒有一致的方式來處理IOException
。 如果觸發了異常,則只需讀取堆棧跟蹤。
我不知道為什么會這樣,但是問題似乎是我沒有輸入文件的完整路徑,即使該文件位於同一文件夾中也是如此。 理想情況下,如果文件位於同一文件夾中,則無需輸入完整的路徑名。
嘗試先檢查是否存在:
File file = new File("test.txt");
if (!file.exists()) {
System.err.println(file.getName() + " not found. Full path: " + file.getAbsolutePath());
/* Handling code, or */
return;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
/* other code... */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.