簡體   English   中英

指定目錄時出現Java.io.FileNotFoundException

[英]Java.io.FileNotFoundException when specifying a directory

我正在嘗試使用名為“ helloworld”的txt文件在Java中定義文件。 我已將此文件放置在資源文件夾中,並且在制作文件時,我將其定義為:

File file = new File("/helloworld");

但是我在編譯時收到此錯誤

 Exception in thread "main" java.io.FileNotFoundException: /helloworld 
    (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileReader.<init>(FileReader.java:72)
    at Tests.main(Tests.java:15)

如果可以幫助解決此問題,這是我嘗試執行的全部代碼

// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
public class Tests
{
  public static void main(String[] args)throws Exception
  {


      File file = new File("/helloworld");

      BufferedReader br = new BufferedReader(new FileReader(file));

      String st;
      while ((st = br.readLine()) != null)
        System.out.println(st);
  }
}

感謝您的幫助!

 public File​(String pathname) 

通過將給定的路徑名​​字符串轉換為抽象路徑名來創建新的File實例。 如果給定的字符串為空字符串,則結果為空的抽象路徑名。

您正在嘗試創建一個新的File實例,但是找不到名為helloworld的文件或某些其他原因。 這就是為什么你會得到錯誤,

 Exception in thread "main" java.io.FileNotFoundException: /helloworld
  1. 命名文件不存在。
  2. 命名文件實際上是一個目錄。
  3. 由於某種原因,無法打開指定文件進行讀取。

您說您嘗試定義一個文件,但是您的代碼似乎可以讀取。 如果要創建文件 ,請嘗試以下一種,

import java.io.*;
import java.nio.charset.StandardCharsets;


class TestDir {
    public static void main(String[] args) {
        String fileName = "filename.txt";

        try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(fileName), StandardCharsets.UTF_8))) {
            writer.write("write something in text file");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

這很容易診斷:您指定的路徑以斜杠開頭,因此,意味着該文件應位於文件系統的根目錄中。 您最好先去除斜線,然后:

  • 在文件所在的同一目錄中啟動程序。
  • 實例化File對象時,請在代碼中指定絕對/相對路徑。

如果該文件位於資源文件夾中並打算與程序捆綁在一起,則需要將其視為資源而不是文件。

這意味着您不應使用File類。 您應該使用Class.getResourceClass.getResourceAsStream方法讀取數據:

BufferedReader br = new BufferedReader(
    new InputStreamReader(
        Tests.class.getResourceAsStream("/helloworld")));

如果要將程序作為.jar文件分發,則這一點尤其重要。 .jar文件是壓縮的歸檔文件(實際上是具有不同擴展名的zip文件),其中包含已編譯的類文件和資源。 由於它們都被壓縮到一個.jar文件中,因此它們根本不是單獨的文件,因此File類無法引用它們。

盡管File類對於您要執行的操作沒有用,但是您可能需要研究絕對文件名相對文件名的概念 通過使用/開頭文件名,您可以指定一個絕對文件名,這意味着您要告訴程序在一個特定的位置查找該文件-幾乎可以肯定不會駐留該文件的位置。

嘗試下面以了解程序正在尋找的文件夾或文件的路徑在哪里

System.out.println(file.getAbsolutePath());

File file = new File("/helloworld");

我認為您的程序正在尋找c:\\helloworld ,並且C盤中沒有文件或文件夾的名稱是helloword

如果將helloword.txt放入C盤,並且

File file = new File("C:\\helloworld.txt");

FileNotFoundException將消失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM