user3788930
user3788930

Reputation: 15

Creating and Writing to a File

if (!file.exists())
  file.mkdirs();
  file.createNewFile();

The error states that I have a problem with actually 'writing' Go Falcons to the file, it will state that the file access is denied, Does that mean something is wrong with my code?

Error states: FileNotFoundException Access is denied

PS: how do I actually read this file, once it's writable?

Upvotes: 0

Views: 135

Answers (4)

Change:

if (!file.exists())
  file.mkdirs();
  file.createNewFile();

To:

if (!file.exists()) {
  file.createNewFile();
}

But first, go read some tutorials or articles. Why are you extending Exception?

Upvotes: 1

Dhan
Dhan

Reputation: 42

You can take the substring of the path till folder structure(excluding file name) and create directories using method mkdirs(). Then create file using createNewFile() method. After that write to newly created file. Don't forget to handle exceptions.

Upvotes: 0

azurefrog
azurefrog

Reputation: 10945

Your problem is that right before you attempt to create your output file, you first create a directory with the same name:

            if (!file.exists())
                file.mkdirs();      // creates a new directory
            file.createNewFile();   // fails to create a new file

Once you've already created the directory, you can no longer create the file, and of course, you cannot open a directory and write data to it as if it were a file, so you get an access denied error.

Just delete the file.mkdirs(); line and your code will work fine:

        if (!file.exists())
            file.createNewFile();   // creates a new file

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201409

If I understand your question, one approach would be to use a PrintWriter

public static void main(String[] args) {
  File outFile = new File(System.getenv("HOME") // <-- or "C:/" for Windows.
      + "/hello.txt");
  try {
    PrintWriter pw = new PrintWriter(outFile);
    pw.println("Go Falcons");
    pw.close();
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
}

Which creates a single line ascii file in my home folder named "hello.txt".

$ cat hello.txt
Go Falcons

Upvotes: 1

Related Questions