52

I am trying to create a folder for each username a user logs in as. Currently I have

private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
File theFile = new File(destination + username); // will create a sub folder for each user 

but the File theFile bit does not create a new folder for the username. How would I do this ?

I have tried

private String destination;

public void File() 
{
    destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
    File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution) 
    theFile.mkdirs();
}

but I need to use the destination later on in the program, how would I do that?

This is my whole code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package richard.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.io.File;
import org.primefaces.event.FileUploadEvent;

@ViewScoped
@ManagedBean(name = "fileUploadController")
public class FileUploadController {

    /*
     public void handleFileUpload(FileUploadEvent event) {
     System.out.println("called");
     FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
     FacesContext.getCurrentInstance().addMessage(null, msg);
     }
     }
     */
    private String username;
    private String destination;

    @PostConstruct
    public void init() {
        System.out.println("called get username");
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }

    public void File() {
    destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
    File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution) 
    theFile.mkdirs();
}

    public File getDirectory(String destination, String username) {
        System.out.println("called get directory");
        // currently not working, is not calling the username or destination 
        //set the user directory from the destinarion and the logged user name
        File directory = new File(destination, username);
        //check if the location exists
        if (!directory.exists()) {
            //let's try to create it
            try {
                directory.mkdir();
            } catch (SecurityException secEx) {
                //handle the exception
                secEx.printStackTrace(System.out);
                directory = null;
            }
        }
        return directory;
    }

    public void handleFileUpload(FileUploadEvent event) {
        System.out.println("called handle file");
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded."); //Displays to user on the webpage
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            //handle the exception
            e.printStackTrace();
        }
    }

    public void copyFile(String fileName, InputStream in) {
        try {


            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(destination + fileName)); // cannot find path when adding username atm
            System.out.println("Called CopyFile"); //testing 
            System.out.println(destination + fileName);

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
            System.out.println("New file created!");//testing
        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
}

FINAL EDIT (Hopefully)

 public void copyFile(String fileName, InputStream in) {
        try {

            destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads
            File theFile = new File(destination + "/" + username); 
            theFile.mkdirs();// will create a sub folder for each user (currently does not work, below hopefully is a solution) (DOES NOW WORK)

            System.out.println("Completed File");
            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(destination + fileName)); // cannot find path when adding username atm
            System.out.println("Called CopyFile"); //testing 
            System.out.println(destination + fileName);

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();
//make sure new file is created, (displays in glassfish server console not to end user)
            System.out.println("New file created!");//testing
        } catch (IOException e) {
            e.printStackTrace();

            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
}

Just how can i print out the new destination and use this later on as currently it creates the new folder but does not select it to use

EDIT SOLVED THIS TOO :

    NewDestination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/" + username;

Added the above code and now it all works

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
user1924104
  • 891
  • 2
  • 16
  • 38
  • 1
    possible duplicate of [Create whole path automatically when writing to a new file](http://stackoverflow.com/questions/2833853/create-whole-path-automatically-when-writing-to-a-new-file) – Mr Tsjolder from codidact Sep 02 '15 at 07:41

4 Answers4

120

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • silly question, im still extremly new at java, but how do i use mkdirs? ive looked at a few examples and they are all used in different ways – user1924104 Feb 02 '13 at 20:49
  • 1
    @user1924104.. Add a `import java.io.File` at the top of your `.java` file. – Rohit Jain Feb 02 '13 at 20:51
  • Thanks ive done that is it simply `private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads File theFile.mkdirs(); = new File(destination + username); // will create a sub folder for each user` – user1924104 Feb 02 '13 at 20:53
  • 1
    @user1924104.. No that is not the way. Your original two lines will be as it is. That will create a file object. And then add this as your 3rd line - `theFile.mkdirs();`. Just this thing. It will create the directory for that file object. – Rohit Jain Feb 02 '13 at 20:54
  • Thank you very much for the explaination – user1924104 Feb 02 '13 at 20:56
  • i get expected when i add in `theFile.mkdirs();` i have used import `java.io.File;` – user1924104 Feb 03 '13 at 01:34
  • 12
    Be carefully to don´t create a new File with the final file name, and run mkdirs, because you finish with a folder on that name: `(new File(c://thepath//the.file)).mkdirs()` >> * C:\thepath\the.file\ * – Elidio Marquina Jun 26 '15 at 03:27
  • 5
    Following @ELD, you should create a folder to the parent level (`getParentFile()`) to avoid ending with a folder with the that name: `(new File(c://thepath//the.file)).getParentFile().mkdirs()` – toto_tico Feb 19 '16 at 18:38
20

Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();
Shashi Ranjan
  • 1,491
  • 6
  • 27
  • 52
  • Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – abarisone Jun 21 '16 at 06:16
  • this answers the question how to create a file from a string in a foolproof manner – Mishax Jun 07 '17 at 07:23
18

A nice Java 7+ answer from Benoit Blanchon can be found here:

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));
Community
  • 1
  • 1
dlauzon
  • 1,241
  • 16
  • 23
  • Is this better than `mkdirs` somehow? – Joshua Pinter Oct 13 '19 at 02:11
  • @JoshuaPinter Apart from having a clearer name, `createDirectories` will consistently throw an Exception if something goes wrong. `mkdirs` on the other hand might just return `false` and you're stuck with having extra code to handle the return value. Also, your `Path` variable can be used elsewhere in the code and use all the power of NIO (instead of relying on the old `File`). – dlauzon Oct 15 '19 at 15:01
0

If you have a large hierarchy of stacked, non-existent directories, you must first call Files.createDirectories(..). For example, in Kotlin it may look like this:

fun File.createFileWithParentDirectories() {
    if(this.exists())return
    val parent = this.parentFile
    if(!parent.exists()) Files.createDirectories(parent.toPath())
    this.createNewFile()
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Viktor Sirotin
  • 169
  • 1
  • 8