簡體   English   中英

我知道的文件的FileNotFoundException在目錄中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM