-1

I get this exception when I try to read from a file:

ERROR:
Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.util.Scanner.<init>(Scanner.java:611)
    at Postal.main(Postal.java:19)


import java.util.Scanner;
import java.io.*;

public class Postal   { 

    public static void main(String[] args) throws Exception   {
        /*** Local Variables ***/
        String line;
        Scanner filescan;
        File file = new File("newfile.txt");
        filescan = new Scanner(file);
        userInfo book = new userInfo();

        /*** Loop through newfile.txt ***/
        while (filescan.hasNext())   {
          line = filescan.nextLine();
          book.addNew(line);
        }

        book.print(0);
    }

}
user207421
  • 305,947
  • 44
  • 307
  • 483
gangwerz
  • 435
  • 2
  • 8
  • 18

3 Answers3

0

The class Scanner uses a FileInputStream to read the content of the file. But it can't find the file so a exception is thrown. You are using a relative path to the file, try out an absolute one.

Crigges
  • 1,083
  • 2
  • 15
  • 28
0

Use this instead:

File file = new File(getClass().getResource("newfile.txt"));
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
-1

Provide an absolute path the location where you want to create the file. And check that user has rights to create file there. One way to find the path is:

File f = new File("NewFile.txt");
if (!f.exists()) {
    throw new FileNotFoundException("Failed to find file: " + 
        f.getAbsolutePath());
}

Try this to open file:

File f = new File("/path-to-file/NewFile.txt");
spooky
  • 1,620
  • 1
  • 13
  • 15