[英]FileNotFoundException for a file I know is in the directory
在下面的程序中,我尝试从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")) ;
对文件使用绝对路径是解决问题的另一种方法,但这是不规则的做法。
您需要注意代码中的路径复杂性,尤其是在使用IDE的情况下,因为IDE可以具有不同的执行路径
根据您的代码,如果值inputFileName
只是文件名(假设为log.txt )并且执行路径实际上不同,那么您的代码将永远找不到该路径
快速证明这一点的最快,最肮脏的解决方案是使用完整的绝对路径作为inputFileName
的值,例如:
String inputFileName = "/var/tmp/log.txt"
要么
String inputFileName = "C:/workspace/temp/log.txt"
验证您的代码可以读取文件后,即可开始处理路径问题,祝您好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.