Java error reading file

So there is the code:

public class Main{
  public static void main(String[] argv) throws IOException{
    new Main().run();
  }
  PrintWriter pw;
  Scanner sc;
  public void run() throws IOException{
    sc = new Scanner(new File("input.txt"));
    int a=sc.nextInt();
    pw = new PrintWriter(new File("output.txt"));
    pw.print(a*a);
    pw.close();
  }
}

      

Mistake:

Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at Main.run(Main.java:14)
    at Main.main(Main.java:8)

      

As I understand it, it cannot find a file named input.txt BUT! I have this file in the same directory as the main class, what could be a failure then? ps Tried on cmd and eclipse, both give the same error.

+3


source to share


3 answers


You probably need to specify the PATH for your file, one thing you can do is check for existence and readability with File.canRead()

, for example

File file = new File("input.txt");
if (!file.canRead()) {
    System.err.println(file.getCanonicalPath() + ": cannot be read");
    return;   
}

      



An example of using PATH could be (for Windows) -

File file = new File("c:/mydir/input.txt");

      

0


source


it does not belong to your main class, it is relative to where you are starting this Java program from (i.e. the current working directory)

it's about



System.getProperty("user.dir")

      

+4


source


You can use System.out.println(System.getProperty("user.dir"))

to see where Java looks for the default file. This is most likely your project folder. This means that you need to put the file if you do not want to specify an absolute path.

0


source







All Articles