Java 如何在 JSF 和 PrimeFaces 中上传和读取文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18609906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:30:13  来源:igfitidea点击:

How to uploaded and read text file in JSF and PrimeFaces?

javajsffile-uploadprimefacesreadfile

提问by Fatih

I need to upload and read a text file with PrimeFaces and JSF. My question is that when I uploaded the text file, where is it stored?

我需要使用 PrimeFaces 和 JSF 上传和读取文本文件。我的问题是,当我上传文本文件时,它存储在哪里?

Here is my .xhtmlfile:

这是我的.xhtml文件:

<p:fileUpload value="#{send.file }" mode="simple" />
</h:form>
<p:commandButton actionListener="#{send.upload}"  value="Send" ajax="false" />

And Java class:

和 Java 类:

public class Send {
    private UploadedFile file;

    public void upload() {
        if (file != null) {
            FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
}

I also found this example to read the file:

我还发现这个例子来读取文件:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("C:\testing.txt")))
        {
            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

My other question is in this example "C:\\testing.txt"is given as a path? Which address I must give to read my uploaded file?

我的另一个问题是在这个例子中"C:\\testing.txt"是作为路径给出的?我必须提供哪个地址才能阅读我上传的文件?

采纳答案by BalusC

when I uploaded the text file, where is it stored?

当我上传文本文件时,它存储在哪里?

This is actually none of your business and you should not be interested in that from inside your JSF backing bean code. It's stored (partial) in memory and/or (partial) in server's temporary storage location which will be wiped/cleaned at intervals. It's absolutely not intented as permanent storage location. You should in the action/listener method just read the uploaded file content and store it in the permanent storage location to your choice.

这实际上与您无关,您不应该对 JSF 支持 bean 代码中的内容感兴趣。它(部分)存储在内存中和/或(部分)存储在服务器的临时存储位置,该位置将定期擦除/清理。它绝对不是永久存储位置。您应该在 action/listener 方法中读取上传的文件内容并将其存储在您选择的永久存储位置。

E.g.

例如

private static final File LOCATION = new File("/path/to/all/uploads");

public void upload() throws IOException {
    if (file != null) {
        String prefix = FilenameUtils.getBaseName(file.getName()); 
        String suffix = FilenameUtils.getExtension(file.getName());
        File save = File.createTempFile(prefix + "-", "." + suffix, LOCATION);
        Files.write(save.toPath(), file.getContents());
        // Add success message here.
    }
}

Note that the FilenameUtilsis part of Apache Commons IO which you should already have installed as it's a required dependency of <p:fileUpload>. Also note that File#createTempFile()does in above example not exactly generate a temp file, but it's just been used to generate an unique filename. Otherwise, when someone else coincidentally uploads a file with exactly the same name as an existing one, it would be overwritten. Also note that Files#write()is part of Java 7. If you're still on Java 6 or older, grab Apache Commons IO IOUtilsinstead.

请注意,这FilenameUtils是 Apache Commons IO 的一部分,您应该已经安装了它,因为它是<p:fileUpload>. 另请注意,File#createTempFile()上面示例中的 do 并没有完全生成临时文件,而只是用于生成唯一的文件名。否则,当其他人偶然上传与现有文件名称完全相同的文件时,该文件将被覆盖。另请注意,这Files#write()是 Java 7 的一部分。如果您仍在使用 Java 6 或更旧版本,请IOUtils改用Apache Commons IO 。

回答by John Velandia

please take a look at this thread that is related to the same issue: how to upload file to http remote server using java?.

请查看与同一问题相关的线程: how to upload file to http remote server using java? .

Please if it does not help you, let me know, and I will go through. ;)

如果它对您没有帮助,请告诉我,我会通过。;)

回答by fjkjava

I red the file this way

我以这种方式红色文件

private UploadedFile file;

public void upload() {
    if (file != null && !"".equals(file.getFileName())) {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputstream(), "UTF-8"))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (Exception ex) {
            LOG.error("Error uploading the file", ex);
        }
    }
}