下载创建的文件csv

时间:2017-11-20 11:05:59

标签: java csv opencsv writer

我正在使用opencsv库创建一个文件csv,但是我遇到了一些困难。 我按照教程在线阅读:

private void exportProducts() {

    String OBJECT_LIST_SAMPLE = "C:/tmp/object-list-sample.csv";

     try (
             BufferedWriter  writer = Files.newBufferedWriter(Paths.get(OBJECT_LIST_SAMPLE));

                CSVWriter csvWriter = new CSVWriter(writer,
                        CSVWriter.DEFAULT_SEPARATOR,
                        CSVWriter.NO_QUOTE_CHARACTER,
                        CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                        CSVWriter.DEFAULT_LINE_END);
            ) {
                String[] headerRecord = {"Name", "Email", "Phone", "Country"};
                csvWriter.writeNext(headerRecord);

                csvWriter.writeNext(new String[]{"Sundar Pichai ♥", "sundar.pichai@gmail.com", "+1-1111111111", "India"});
                csvWriter.writeNext(new String[]{"Satya Nadella", "satya.nadella@outlook.com", "+1-1111111112", "India"});

            } catch (IOException e) {
                LOG.error("", e);
            }

}

一切都很好,文件创建正确,但我想扩展这个。我的意思是

  1. 我不想使用OBJECT_LIST_SAMPLE,但我想创建一个临时文件(File.creteTempFile),用它来写字符串
  2. 最后,我想直接为用户下载此文件。
  3. 请帮助我!

    由于

1 个答案:

答案 0 :(得分:0)

如何使用Files.createTempFile

在临时文件上创建BufferedWriter
Path tempDir = Files.createTempFile("Products", "sample.csv");
BufferedWriter writer = Files.newBufferedWriter(tempDir, StandardOpenOption.DELETE_ON_CLOSE);

这是一个简单的例子:

public static void main(String[] args) throws Exception {
    Path p = Files.createTempFile("Test", ".tmp");
    try(
            BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.DELETE_ON_CLOSE)
            ){
        System.out.println(p);
        for(int i = 0; i < 26; ++i){
            writer.append((char)(i+'a'));
        }

    }
}

创建“c:\ Temp \ Test #########。tmp”,其中包含:

 abcdefghijklmnopqrstuvwxyz

对于第二部分,没有足够的信息。