在下面的程序中,我尝试读取 Hw1_1.java 源代码。我每次都会收到 FileNotFoundException (可能有充分的理由)。我知道该程序尚未完成,因为我只是试图阻止出现异常。我很茫然。
如果有人能指出我正确的方向,我将不胜感激。
package hw1_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Hw1_1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the name of a java source code file");
String inputFileName = console.next();
String outputFileName = (inputFileName + ".txt");
try {
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
while ( in .hasNextLine()) {
String line = console.nextLine();
out.println(line);
}
in .close();
out.close();
} catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
}
}
最佳答案
这确实是个好主意 - 首先检查 java 程序的用户目录。了解后,您就可以轻松调试 FileNotFoundException 问题。
您可以通过以下代码简单地打印用户目录。
System.out.println(System.getProperty("user.dir")) ;
使用文件的绝对路径是解决问题的另一种方法,但这有点不规则。
关于java - 我知道目录中存在一个文件的 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973157/