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 to share