为什么我的应用程序中的所有文件都写入jboss tmp目录?

时间:2012-03-19 18:55:21

标签: java file jsf jboss writing

我的Bean中有这样的功能:

public String uploadFile(UploadedFile uploadedFile) {
    logger.info("Enter: uploadFile(UploadedFile uploadedFile).");
    String name = uploadedFile.getName();
    String extension = name.substring(name.length() - 3);
    if (extension.contentEquals("peg")) {
        extension = "jpeg";
    }

    RandomString rs = new RandomString(RANDOM_PHOTO_NAME_LENGTH);
    this.randomPhotoName = rs.nextString();

    String fileName = this.randomPhotoName + "." + extension;
    logger.info("File name: " + name + ". Extension: " + extension + ". New fileName: " + fileName);
    ServletContext sc = (ServletContext) FacesContext.getCurrentInstance()
            .getExternalContext().getContext();

    File f = new File(
            sc.getRealPath(Constant.USER_FILE_PATH));
    if (!f.exists()) {
        logger.info("Folder "
                + Constant.USER_FILE_PATH
                + " nie istniej. Tworze nowy.");
        f.mkdirs();
    }
    File backupFile = new File(
            sc.getRealPath(Constant.USER_FILE_PATH
                    + fileName));

    InputStream in = null;
    OutputStream out = null;
    try {
        in = new BufferedInputStream(uploadedFile.getInputStream());
        out = new FileOutputStream(backupFile);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
    } catch (IOException ioe) {
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage msg = null;
        msg = new FacesMessage(
                "Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.");

        context.addMessage(null, msg);
        logger.error(
                "Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.",
                ioe);
    } finally {
        try {
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    logger.info("Exit: uploadFile(UploadedFile uploadedFile).");
    return fileName;
}

所有文件都保存在tmp目录中,例如:

\jboss-5.1.0.GA\server\default\tmp\a006-czo4uq-gzzu4l42-1-gzzuk7xr-a2\TupTus.war\media\img\user-gallery\6u2fpgu3tkzniwg.JPG

1 个答案:

答案 0 :(得分:4)

因为所有文件都构建为:

File backupFile = new File(
            sc.getRealPath(Constant.USER_FILE_PATH
                    + fileName));

听起来像sc.getRealPath()返回JBoss为您的应用程序分配的工作目录。

所以,真正的问题是你:你想在哪里写文件?如果没有,那么在哪里?如果您更喜欢用户临时目录,请使用new File(System.getProperty("java.io.tmpdir"), fileName)并在那里写。

如果您希望能够配置开箱即用的路径,您可以将此路径存储在DB或配置文件中,或者在使用命令行开关-D运行JBoss时通过自定义系统属性传递它