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

标签 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 中

这是我当前的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 notused

当前代码:

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

再次编辑哈哈:

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

这是我最新版本的代码,我尝试修改它,但它当前抛出一些错误,我已在代码中的注释中添加了错误,也是 public File getDirectory(String destination) ,字符串用户名) 在正确的位置?谢谢,我从来没想过我需要做这么多工作才能做一些简单的事情! :D

最佳答案

您的问题与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();
        }
    }
}

关于java - 如何在目的地中使用字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614475/

相关文章:

java - 使用 vertx 将 Mongo 集合流式传输到 Kafka 主题的方法应该是什么?

java - 使用 Spring Security 保护方法

java - 为什么国际化不能正常运作?日本科学基金会

JSF commandLink,POST和后退按钮

java - 单击复选框后面板重新加载

java - 是否有在监听器的句柄方法中调用 Controller 类的方法的最佳实践方法?

java - 从文本文件中读取并存储在字符串中

java - 有没有办法将数字(在我的例子中是 double )转换为java中的复数?

Java Applet 不显示圆圈

java - 通过id获取组件的值?