简体   繁体   中英

FileNotFoundException for a file I know is in the directory

In the following program I am trying to read from the Hw1_1.java source code. I get a FileNotFoundException every time (probably for a good reason). I know the program isn't complete as I am just trying to stop getting the exception. I am at a loss.

If someone could point me in the right direction I would greatly appreciate it.

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");
        }
    }
}

It's really a good idea - to first check the user directory of your java program. Once you know, you can easily debug the FileNotFoundException issue.

You can simply print the user directory from following code.

System.out.println(System.getProperty("user.dir")) ;

Using absolute path for the file is another way of solving problem, but that's a little irregular way of doing.

You need to be aware of path complexity in your code, especially if you are using IDE as IDE can have a different execution path

Based on your code, if the value inputFileName is just the file name (let's say log.txt ) and the execution path is actually different, then your code will never find the path

The quickest and dirty solution to quickly prove this is to use the full absolute path as the value of inputFileName for example:

String inputFileName = "/var/tmp/log.txt"

or

String inputFileName = "C:/workspace/temp/log.txt"

Once this verifies that your code can read the file, then you can start handling the path issue, good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM