-1

I am new to Java and come from a C++ background. I made a really simple code just to test out file reading. I have an input file called "input.txt" and its in the same file as my main file called "Main.java". However, when I try to create a new instance of a File object using the name "input. txt", it does not find the file and file.exists() returns false. When I instead put the full path name, it does find the file. The code is displayed below:

 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();

    }
}

Am I doing something wrong here because I do not see why I shouldn't be able to just enter the file name instead of the full path. In C++, if the files were in the same folder I could just enter the file name so I'm confused as to why that is not working here. Below is the output I get:

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)

Can anyone help me understand what is going on? Any help would be greatly appreciated.

  • Or this: [Java, reading a file from current directory?](https://stackoverflow.com/q/1480398/12323248) – akuzminykh Dec 17 '20 at 15:57
  • Identifying and organizing files -> https://en.wikipedia.org/wiki/Computer_file#Identifying_and_organizing – fantaghirocco Dec 17 '20 at 15:58
  • Briefly, the Java compiler does not (necessarily) compile in-place - it moves the file to a different folder. But, that file resource is not moved - so the compiled version is not found. There are several ways to solve the problem as all the duplicate questions/answers show. – Randy Casburn Dec 17 '20 at 16:01

1 Answers1

0

You can see where the path resolves to (which will be the dir held in System property "user.dir") as follows:

System.out.println(Path.of("index.txt").toRealPath());
DuncG
  • 12,137
  • 2
  • 21
  • 33