在try catch中找不到文件

问题描述 投票:0回答:1

我的代码想在我的桌面上找到该文件,该文件由“ project.csv”保存,但找不到。

public static void main(String[] args) {

    Scanner in= new Scanner(System.in); 
    Scanner fileIn = null;

    PrintWriter fileOut = null;

    try {
        fileIn = new Scanner(new FileReader("project.csv"));
    } catch (FileNotFoundException e) {
        System.out.print("File is missing. Please try again: ");
        String fileName = in.nextLine();
    try {
        fileIn = new Scanner(new FileReader(fileName));
    } catch (FileNotFoundException e1) {
        System.out.println("File is not found. Exiting!");
        System.exit(1);
    }
    } 

}

}

java try-catch filenotfoundexception
1个回答
0
投票

new FileReader("project.csv")告诉读者在当前工作目录中搜索文件,这很可能是您的用户文件夹。要在桌面上获取文件,请执行:

new FileReader("/desktop/project.csv")

但是为了安全起见,我将使用绝对路径并将该路径也包含到用户目录中:

new FileReader(System.getProperty("user.home") + "/desktop/project.csv")
© www.soinside.com 2019 - 2024. All rights reserved.