簡體   English   中英

Java找不到文件?

[英]Java Cannot find file?

嗨,我正在嘗試設置掃描儀以打印出文本文件的內容。 這是我的代碼:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerReadFile {

    public static void main(String[] args) {

        // Location of file to read
        File file = new File("CardNative.java.txt");

        try 
        {

                Scanner scanner = new Scanner(file);

                while (scanner.hasNextLine()) 
                {
                    String line = scanner.nextLine();
                    System.out.println(line);
                }
                scanner.close();
        } 
        catch (FileNotFoundException e) 
        {
              e.printStackTrace();
        }

    }
}

我在項目中創建了一個源文件夾,並將文本文件放在其中。 但是我不斷收到此錯誤:

java.io.FileNotFoundException: CardNative.java.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at java.util.Scanner.<init>(Scanner.java:636)
    at ScannerReadFile.main(ScannerReadFile.java:14)

您可以使用use System.out.println(System.getProperty("user.dir")); 查看Java在默認情況下正在尋找哪個文件夾的文件。
如果文件不存在,則必須指定文件的完整路徑。

這應該工作。

public static void main(String[] args) {


            Scanner scanner = new Scanner(ScannerReadFile.class.getResourceAsStream("CardNative.java.txt"));

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();

    }
}

您需要確保將文件放置在與運行程序相同的目錄中。 嘗試將其添加到主要功能的頂部,以查看當前目錄是什么,以及文件是否實際在該目錄中:

System.out.println(System.getProperty(“ user.dir”));

new File(String pathname);

您正在使用的coinstructor將文件路徑作為參數,絕對或相對。 如果是相對的,它將是執行路徑/ your_string。 因此,應將文件與已編譯的.jar文件放在同一文件夾中。

File file1 = new File("text.txt");
File file2 = new File("D:/documents/test.txt");

如果程序是從C:/programms/myprj.jar執行的,則file1將打開“ C:/programms/test.txt”,而file2將打開“ D:/documents/test.txt”,而與執行路徑無關。

http://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.lang.String)

我在評論中張貼了我的答案,但由於我的聲譽不足,因此我無法發表評論。 就像您的注釋一樣,您在文件路徑中使用反斜杠。 而是使用雙反斜杠\\或一個正斜杠/。 例如C:/java/file.txt您應該為它提供文件的正確和實際路徑,或者確保文件位於源所在的位置。

public class ScannerReadFile {

    public static void main(String[] args) {

        // Location of file to read
        File file = new File("C:/Users/EastCorporation/Desktop/CardNative.java.txt");

        try {

            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

暫無
暫無

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

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