如何在目的地中使用字符串?

时间:2013-01-30 21:49:23

标签: java jsf

希望是一个简单的问题:

我已创建代码以从登录页面获取用户名:

private String username;

@PostConstruct
public void init() {
    username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}

但我想要做的是将用户名添加到此目的地的末尾:

private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/";

我该怎么做,所以目的地会调用用户名将文档放在特定于该用户的文件中?这都在同一个豆子里

这是我目前的bean

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

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    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 

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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


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

            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!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

当前编辑:

/*
 * 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.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

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

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    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 

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public File getDirectory(String destination, String username) {
        //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 copyFile(String fileName, InputStream in) {
        try {


            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(directory)); // cannot find path when adding username atm
            System.out.println(directory); //testing 

            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!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

编辑::::

现在说out = new FileOutputStream(new File(directory));中的目录无法找到符号,我也没有使用realFile

当前代码:

/*
 * 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.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

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

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    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 (currently does not work, below hopefully is a solution) 

    public File getDirectory(String destination, String username) { // currently not working, is not calling the username or directory 
        //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) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        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) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        OutputStream out = null;
        try {
            File realFile = new File(userDirectory, fileName);
            out = new FileOutputStream(new File(directory));
            int read = 0;
            //1024 must be a constant
            //also, it must be 4098 (4 KBs) for better performance
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            out.close();
        }
    }
}

再次编辑LOL:

/*
 * 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.context.FacesContext;

import org.primefaces.event.FileUploadEvent;

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

    private String username;

    @PostConstruct
    public void init() {
        username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    }
    private String destination = "C:/Users/Richard/printing~subversion/fileupload/web/WEB-INF/uploaded/"; // main location for uploads (will change this thanks to adivce )
    File theFile = new File(destination + username); // will create a sub folder for each user (currently does not work, below hopefully is a solution) 

    public File getDirectory(String destination, String username) { 
        // 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) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        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) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        OutputStream out;
        try {
            File realFile = new File(userDirectory, fileName);//realFile variable not used
            out = new FileOutputStream(new File(userDirectory));// no suitable constructor found for File(File)
            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();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
}

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


            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(directory)); // cannot find path when adding username atm
            System.out.println(directory); //testing 

            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!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
*/

这是我最新版本的代码,我试图修改它,但它当前抛出了一些错误,我在代码中的注释中添加了错误,也是公共文件getDirectory(String destination, String username)中的正确的地点 ?谢谢,我从来没有想过我会做这么多工作来做一些简单的事情! :d

1 个答案:

答案 0 :(得分:1)

您的问题与File类使用情况更相关,而不是JSF问题。

您可以使用此类来处理文件或目录。首先,您可以使用两种方法:

  • 将检索用户目录的方法

  • 将文件保存在用户目录中的方法

基本示例:

//note: this must be moved to an utility class
public File getDirectory(String destination, String username) {
    //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
            //this is a naive way to do it
            secEx.printStackTrace(System.out);
            directory = null;
        }
    }
    return directory;
}

public void saveFile(String fileName, byte[] data) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        //create the real file using the directory as parent directory
        //we'll give the file name too
        //check the different constructors for File class
        File realFile = new File(userDirectory, fileName);
        //save the file the way you want/need...
        //this should be also in an utility class
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(realFile);
            fos.write(myByteArray);
        } catch (Exception ex) {
            //handle the exception
            ex.printStackTrace(System.out);
        } finally {
            if (fos != null)
                fos.close();
        }
    }
}

参考文献:


根据您的问题编辑,您必须修改copyFile,以便将其视为我提议的saveFile方法。我将更改实施以使用InputStream

public void copyFile(String fileName, InputStream in) {
    //get the directory assigned to the current user
    File userDirectory = getDirectory(destination, username);
    if (userDirectory != null) {
        OutputStream out;
        try {
            File realFile = new File(userDirectory, fileName);
            out = new FileOutputStream(new File(userDirectory));
            int read = 0;
            //1024 must be a constant
            //also, it must be 4098 (4 KBs) for better performance
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            out.close();
        }
    }
}