Search code examples
javafileio

Catch FileNotFoundException although I do try put the input.txt in ANY directory?


When I create a "input.txt" as well and store it as the same directory as the java files. Location as below:

Java file: D:\workspace\Hello\src\io\Letter.java

Text file: D:\workspace\Hello\src\io\input.txt

I get the error FileNotFoundException. Then I tried putting the text file anyway then try running the code but it doesn't work.

Then the question get solved when the whole directory being used.

//Before
package io;
import java.io.*;
public class Letter {

   public static void main(String args[]) throws Exception {  
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }

   }

}


//After
package io;
import java.io.*;
public class Letter {

   public static void main(String args[]) throws Exception {  
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
         in = new FileInputStream("D:\\workspace\\Hello\\src\\io\\input.txt");
         out = new FileOutputStream("D:\\workspace\\Hello\\src\\io\\output.txt");

         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }}}

Finally the answer is putting the whole directory. Why does this work?


Solution

  • When you specify

    in = new FileInputStream("input.txt");
    out = new FileOutputStream("output.txt");
    

    you refer to the directory where your user (in your case your IDE) runs, so the file you are trying to open is at workingDirectory/input.txt

    This is a general behaviour when working with relative file paths.

    Here you can get some more information about that topic: https://docs.oracle.com/javase/tutorial/essential/io/path.html

    Edit: If you use an IDE with a built-in JRE, the path that relative paths point to is your projects directory.