简体   繁体   English

找不到Java文件,但在同一目录中,但捕获了异常

[英]Java File Not Found but in same directory and with caught exceptions

Okay this is weird and ridiculous.. 好吧,这很奇怪和可笑。

I have this really simple code: 我有这个非常简单的代码:

    public static void main(String[] args) throws Exception {
      BufferedReader br = new BufferedReader(new FileReader("input.txt"));
      String s;
      while ((s = br.readLine()) != null) {
        System.out.println(s);
      }
    }

I also tried wrapping the BufferedReader... in a try-catch block. 我还尝试将BufferedReader...包装在try-catch块中。 Why the heck is this throwing this error: 为什么这会引发此错误:

 Exception in thread "main" java.io.FileNotFoundException: /input.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)

It is thrown at the BufferedReader line. 它被抛出在BufferedReader行中。

The file is in the same package / directory as the java file. 该文件与java文件位于相同的包/目录中。 I have tried both declaring a throws Exception and try-catch blocks. 我已经尝试了声明throws Exception和try-catch块。

Whatever I do I keep getting this error. 无论如何,我都会不断收到此错误。

You need to have the file in the working directory from which Java is started. 您需要将文件放在启动Java的工作目录中。 Depending on how you start the program, this could be different. 根据您启动程序的方式,可能会有所不同。

You can print the current working directory with: 您可以使用以下命令打印当前工作目录:

System.out.println(System.getProperty("user.dir"));

Easy way to access any resources from package by using Thread.currentThread().getContextClassLoader().getResourceAsStream("path"); 使用Thread.currentThread().getContextClassLoader().getResourceAsStream("path");从包访问任何资源的简便方法

Example: 例:

InputStream inputstreamFromPackage = Thread.currentThread().getContextClassLoader().getResourceAsStream("<packageName/file.ext>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM