Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Not Created in Java

Tags:

java

I'm sure I'm missing something basic here. I'm trying to create a new file on my drive, but I'm getting an error:

Exception in thread "main" java.io.FileNotFoundException: C:\ProgramData\msena\test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileReader.<init>(FileReader.java:55)
at net.meosoft.relatetoit.core.HibernateSessionFactory.main(HibernateSessionFactory.java:89)

My code at the moment is:

    final File file = new File("C:\\ProgramData\\uname2\\test.txt");
    final BufferedReader in = new BufferedReader(new FileReader(file));
    while(in.ready()) {
        System.out.println(in.readLine());
    }
    in.close();

What's wrong at the moment? I want to just read, even if it's there (so file should be made).

like image 955
halphhurts Avatar asked Nov 22 '25 16:11

halphhurts


2 Answers

Java doesn't automatically check that File() exists, nor will it automatically create it if you ask it.

You'll need to do one of the following:

  1. Add in a check for the file's existence: if(file.exists()) { ... }.
  2. Add in a check, similar to above, but then if it doesn't exist, call: file.createNewFile();. This will make a new file on the file system for you to use.

If that still doesn't work, I'd check you have write permissions to that directory. :)

like image 158
Michael Avatar answered Nov 25 '25 05:11

Michael


The File class represents the path to a file, not the file itself. If the file does not exist (!File.exists()), an exception will be thrown when you try to access it. Make sure the path to the file is correct and that you have permission to read from that location.

If you want to create the file, you can use File.createNewFile().

like image 29
Jeffrey Avatar answered Nov 25 '25 06:11

Jeffrey