java - 如果中间文件夹不存在,则创建中间文件夹

标签 java file

我正在尝试为用户登录的每个用户名创建一个文件夹。目前我有

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 

File theFile 位不会为用户名创建新文件夹。我该怎么做?

我试过了

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

但我需要稍后在程序中使用目的地,我该怎么做?

这是我的全部代码:

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

最终编辑(希望如此)

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

我怎样才能打印出新的目的地并在以后使用它,因为目前它创建了新文件夹但没有选择它来使用

编辑也解决了这个问题:

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

添加了上面的代码,现在一切正常

最佳答案

您必须实际调用一些方法来创建目录。仅仅创建一个 file 对象并不会在文件系统上创建相应的文件或目录。

您可以使用 File#mkdirs()创建目录的方法:-

theFile.mkdirs();

File#mkdir() 之间的区别和 File#mkdirs()就是说,如果中间目录不存在,后者将创建任何中间目录。

关于java - 如果中间文件夹不存在,则创建中间文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14666170/

相关文章:

java - NotReadablePropertyException : Invalid property 'productss' of bean class [java. util.ArrayList]

file - 如何在 TIdMultiPartFormDataStream 中包含文件以与 Indy IdHTTP1.Post 一起使用?

java - 放入 Java 应用程序时如何更改光标

objective-c - 保存文件避免重复文件名和覆盖

java - 从 JFileChooser 获取 file.properties 并在 ResourceBundle 上使用它

java - Java 中的屏幕尺寸

java - 如何使用 setSelectedValue 将多个项目设置为在 JList 中选择?

java - 如何在底部导航布局中添加选项卡布局

node.js - 将文档导出到本地 Google api 时出现问题

Java 同步列表