gpt4 book ai didi

java - Java 读取文件时出错

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:12:42 25 4
gpt4 key购买 nike

所以有代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com