【问题标题】:Create intermediate folders if one doesn't exist如果中间文件夹不存在,则创建中间文件夹
【发布时间】:2013-01-17 22:31:15
【问题描述】:

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

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;

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

【问题讨论】:

标签: java file


【解决方案1】:

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

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

theFile.mkdirs();

File#mkdir() 和File#mkdirs() 的区别在于,如果中间目录不存在,后者会创建任何中间目录。

【讨论】:

  • 非常感谢 :) 将对其进行测试:D
  • @user1924104.. 在 .java 文件的顶部添加 import java.io.File。
  • @user1924104.. 不,那不是办法。您原来的两行将保持原样。这将创建一个文件对象。然后将其添加为您的第三行 - theFile.mkdirs();。就这件事。它将为该文件对象创建目录。
  • 小心不要使用最终文件名创建一个新文件,然后运行 ​​mkdirs,因为您以该名称完成了一个文件夹:(new File(c://thepath//the.file)).mkdirs() >> * C:\thepath\the .file\ *
  • 在@ELD 之后,您应该创建一个到父级别 (getParentFile()) 的文件夹,以避免以具有该名称的文件夹结尾:(new File(c://thepath//the.file)).getParentFile().mkdirs()
【解决方案2】:

如果在创建/编辑文件时中间文件夹不存在,请使用此代码spinet创建中间文件夹:

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

【讨论】:

  • 请编辑更多信息。不鼓励使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。我们在这里努力成为知识的资源。
  • 这回答了如何以万无一失的方式从字符串创建文件的问题
【解决方案3】:

可以在here 找到来自Benoit Blanchon 的Java 7+ 答案:

在 Java 7 中,您可以使用 Files.createDirectories()。

例如:

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

【讨论】:

  • 这是否比 mkdirs 更好?
  • @JoshuaPinter 除了具有更清晰的名称外,createDirectories 在出现问题时会始终抛出异常。另一方面,mkdirs 可能只返回false,而您却不得不使用额外的代码来处理返回值。此外,您的 Path 变量可以在代码中的其他地方使用并使用 NIO 的所有功能(而不是依赖旧的 File)。
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 2011-01-19
  • 2013-09-18
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
相关资源
最近更新 更多