Java无法找到文件?

时间:2014-09-26 09:21:38

标签: java resources java.util.scanner

您好我正在尝试设置扫描仪来打印文本文件的内容。这是我的代码:

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)

5 个答案:

答案 0 :(得分:4)

您可以使用use System.out.println(System.getProperty("user.dir"));查看Java默认查找文件的文件夹。
如果文件不存在,则必须指定文件的完整路径。

答案 1 :(得分:1)

这应该有用。

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();

    }
}

答案 2 :(得分:0)

您需要确保将文件放在运行程序的目录中。尝试在main函数的顶部添加它,以查看当前目录是什么,以及您的文件是否实际位于该目录中:

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

答案 3 :(得分:0)

new File(String pathname);

您正在使用的moneytructor将filepath作为参数,绝对或相对。如果是相对的,则它将是执行路径/ your_string。 因此,您应该将文件放在与编译的.jar文件相同的文件夹中。

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

如果程序正在从C:/programms/myprj.jar执行,那么 file1将打开&#34; C:/programms/test.txt"和file2将打开&#34; D:/documents/test.txt"独立于执行路径。

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

答案 4 :(得分:0)

我在评论中发表了我的回答但我不能发表评论,因为我没有足够的声誉。与评论中一样,您在文件路径中使用反斜杠。而是使用双反斜杠\或一个前进/。例如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();
        }

    }
}
相关问题