파일을 읽을 때 전체 경로를 입력해야하는 이유는 무엇입니까? [복제]

Dec 17 2020

저는 Java를 처음 접했으며 C ++ 배경에서 왔습니다. 파일 읽기를 테스트하기 위해 정말 간단한 코드를 만들었습니다. "input.txt"라는 입력 파일이 있으며 "Main.java"라는 기본 파일과 동일한 파일에 있습니다. 그러나 "input. txt"라는 이름을 사용하여 File 객체의 새 인스턴스를 만들려고하면 파일을 찾지 못하고 file.exists ()가 false를 반환합니다. 대신 전체 경로 이름을 입력하면 파일을 찾습니다. 코드는 다음과 같습니다.

 public static void main(String[] args) throws FileNotFoundException
    {
    //  File file = new File("C:/Users/josep/OneDrive/Documents/java/input.txt"); //This works
        File file = new File("input.txt"); //why won't this work?

        if( file.exists() )
        {
            System.out.println("File exists");
        }
        else
        {
            System.out.println("Doesn't exist"); //this prints out.
        }

        Scanner input = new Scanner(file);

        String str = input.nextLine();
        System.out.println("Str: " + str);

        input.close();

    }
}

전체 경로 대신 파일 이름을 입력 할 수없는 이유를 알 수 없기 때문에 여기서 뭔가 잘못하고 있습니까? C ++에서 파일이 동일한 폴더에 있으면 파일 이름 만 입력 할 수 있으므로 여기에서 작동하지 않는 이유가 혼란 스럽습니다. 다음은 내가 얻는 출력입니다.

Doesn't exist
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
        at java.base/java.io.FileInputStream.open0(Native Method)
        at java.base/java.io.FileInputStream.open(FileInputStream.java:211)
        at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153)
        at java.base/java.util.Scanner.<init>(Scanner.java:639)
        at Main.main(Main.java:22)

누가 무슨 일이 일어나고 있는지 이해하도록 도울 수 있습니까? 어떤 도움이라도 대단히 감사하겠습니다.

답변

DuncG Dec 17 2020 at 23:14

다음과 같이 경로가 확인되는 위치 (시스템 속성 "user.dir"에있는 dir)를 볼 수 있습니다.

System.out.println(Path.of("index.txt").toRealPath());