java - 我知道目录中存在一个文件的 FileNotFoundException

标签 java filenotfoundexception

在下面的程序中,我尝试读取 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/

相关文章:

运行 jar 文件时出现 Java FileNotFoundException

java - 解析问题 : outstanding network connection.

java - 凯撒密码移位问题

java - spring 如何管理原型(prototype) bean 的完整生命周期?

java - maven clean install - 无法在项目 myGoogleAppEngine 上执行目标

java - Eclipse Java Web 服务无法读取文件

java - Mac 上的 RXTX Java Eclipse

java - Java : Encountering ConcurrentModificationException. There's something wrong with my iterators and/or HashMaps, and I don't know what it is

java - 我该如何处理这个 FileNotFoundException?

java - 热加载.jar文件: random FileNotFoundException