web-dev-qa-db-fra.com

Créer des dossiers intermédiaires s'il n'en existe pas

J'essaie de créer un dossier pour chaque nom d'utilisateur sous lequel un utilisateur se connecte. Actuellement j'ai

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 

mais le File theFile bit ne crée pas de nouveau dossier pour le nom d'utilisateur. Comment je ferais ça?

J'ai essayé

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();
}

mais je dois utiliser la destination plus tard dans le programme, comment pourrais-je le faire?

C'est tout mon 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 (avec un peu de chance)

 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);
        }
    }
}

Comment puis-je imprimer la nouvelle destination et l'utiliser plus tard, car elle crée actuellement le nouveau dossier mais ne le sélectionne pas pour utilisation

EDIT RÉSOLU CET AUSSI:

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

Ajout du code ci-dessus et maintenant tout fonctionne

43
user1924104

Vous devez réellement appeler une méthode pour créer les répertoires. Créer simplement un objet file ne créera pas le fichier ou le répertoire correspondant sur le système de fichiers.

Vous pouvez utiliser la méthode File#mkdirs() pour créer le répertoire: -

theFile.mkdirs();

La différence entre File#mkdir() et File#mkdirs() est la suivante: ce dernier créera un répertoire intermédiaire s'il n'existe pas.

112
Rohit Jain

Utilisez ce code spinet pour créer des dossiers intermédiaires s'il n'en existe pas lors de la création/modification d'un fichier:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();
17
Shashi Ranjan

Un Nice Java 7+ réponse de Benoit Blanchon peut être trouvé ici :

Avec Java 7, vous pouvez utiliser Files.createDirectories() .

Par exemple:

Files.createDirectories(Paths.get("/path/to/directory"));
16
dlauzon