ddjh5
ddjh5

Reputation: 67

How to write a file to a directory?

I am trying to write a file to a specific directory in Java. I have looked at many of the already answered questions relating to this in the Stack Overflow forums. Yet, every method I try just ends up with this error:

java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at mainFiles.fileManagers.NewCSV.nJSON(NewCSV.java:40)
at mainFiles.appWindows.UserDashboard$1.run(UserDashboard.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Code:

public static void nJSON(String username) { 

    File file = new File("src/jsonFiles/" +  username + ".json");

    try {
        if (file.exists() && file.isDirectory()) {
            System.out.println(username + ".json exist.");
        } else {
            json.put("Username", username); 
            json.put("Password", mainFiles.windowsSrc.UserInfo.password); 

            file.createNewFile(); 
            FileWriter writer = new FileWriter(file); 
            FileOutputStream os = new FileOutputStream(file); 

            writer.write(json.toJSONString());
            writer.flush();
            os.close(); 
            writer.close();

            System.out.println(username + ".json created.");

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Any suggestions on how I can write my file to a certain directory?

Upvotes: 0

Views: 1241

Answers (2)

RobCo
RobCo

Reputation: 6495

Some remarks about your code:

  1. Create the parent directory before the file. You cannot create a file in a non existent directory.

    file.getParentFile().mkdirs();

  2. Remove the FileOutputStream code. You are using both a FileWriter and FileOutputStream at the same time for the same file. This is a mistake as one may overwrite the other, causing the file to be immediately cleared after being written to.

  3. createNewFile() is not necessary. The FileWriter or FileOutputStream can create it's own file as long as the directory exists (see #1).

  4. Close the writer in a finally block so that you are guaranteed the underlying stream is closed even if an exception occurs during writing.

I'm not sure what the isDirectory check is for. If it exists, surely it would be a file and not a directory. Either way, file.exists() && file.isDirectory() is unnecessary as isDirectory already checks for existence.


Updated code:

public static void nJSON(String username ) {

    File file = new File("src/jsonFiles/" +  username + ".json");

    if (file.isDirectory()) {
        System.err.println(username + ".json exist and is a directory.");
        return;
    }

    if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        System.err.println("Failed to create directory " + file.getParent());
        return;
    }

    FileWriter writer = null;
    try{
        json.put("Username", username);
        json.put("Password", mainFiles.windowsSrc.UserInfo.password);

        writer = new FileWriter(file);
        writer.write(json.toJSONString());
        writer.close();

        System.out.println(username + ".json created.");

    } catch(IOException e){
        e.printStackTrace();
    } finally {
        if(writer != null) {
            try {
                writer.close();
            } catch(IOException ignore) { }
        }
    }
}

Upvotes: 7

Ivan Dejanovic
Ivan Dejanovic

Reputation: 51

Try to run this code:

package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {

    public static void main(String[] args) {
        nJSON("test");
    }

    public static void nJSON(String username) {
        File file = new File("/home/ivan/Downloads/" + username + ".json");
        try {
            if (file.exists() && file.isDirectory()) {
                System.out.println(username + ".json exist.");
            } else {
                String content = "testing";
                file.createNewFile();
                FileWriter writer = new FileWriter(file);
                FileOutputStream os = new FileOutputStream(file);
                writer.write(content);
                writer.flush();
                os.close();
                writer.close();

                System.out.println(username + ".json created.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Just replace home/ivan/Downloads/ with a valid directory path. It is basically your code with out simple json. It works on my machine so I suspect you are trying to write to directory that does not exists.

Upvotes: 0

Related Questions