所以有代码:
public class Main{
public static void main(String[] argv) throws IOException{
new Main().run();
}
PrintWriter pw;
Scanner sc;
public void run() throws IOException{
sc = new Scanner(new File("input.txt"));
int a=sc.nextInt();
pw = new PrintWriter(new File("output.txt"));
pw.print(a*a);
pw.close();
}
}
错误:
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Main.run(Main.java:14)
at Main.main(Main.java:8)
据我所知,它找不到名为 input.txt 的文件,但是!我在主类所在的同一目录中有该文件,那可能是什么问题呢? p.s 在 cmd 和 eclipse 上试过,都给出相同的错误。
最佳答案
它与您的 Main 类无关,它与您启动此 Java 程序的位置(即当前工作目录)相关
相对于
System.getProperty("user.dir")
关于java - Java 读取文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314135/