Java Servlet将表单输入写入CSV

时间:2012-02-20 17:29:56

标签: java export-to-csv bufferedwriter

我正在尝试构建一个解析表单输入并从中创建.csv文件的servlet,但是bufferedWriter对象会截断很多字符,因为没有(显而易见的)原因。

        String filepath = getServletContext().getRealPath("\\") + "temp";
        String filename = "csv"+dateFormat.format(date)+".csv";
        File file = new File(filepath + filename);            
        file.createNewFile();
        BufferedWriter fwrite = new BufferedWriter(new FileWriter(file));
        for(int i=0; i<list.size(); i++) {
            String[] dataEntry = list.get(i);
            for (int j=0; j<dataEntry.length;j++)                 
                 fwrite.write("test1-2");
                //fwrite.append(dataEntry[j]+";");     
            fwrite.newLine();
        }
        fwrite.close();            
         URI fileUri = file.toURI();
         stream = response.getOutputStream();
         response.setContentType("text/csv");
         response.addHeader("Content-Disposition", "attachment; filename="
            + filename);

         URLConnection urlConn = fileUri.toURL().openConnection();
         response.setContentLength((int) urlConn.getContentLength());
         buf = new  BufferedInputStream(urlConn.getInputStream());                          
         while (buf.read() != -1)
            stream.write(buf.read());
        } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();     
        }          
}

很抱歉,如果代码有点slapdash。为每个条目写入“test1-2”字符串时的当前输出是

  

ET-ts12et-ts12et-ts12ÿ

对代码本身的任何进一步评论将不胜感激我只是在试验我在网上找到的东西,我没有实际的最佳实践参考点。

1 个答案:

答案 0 :(得分:1)

我可能会添加一些方法,以免单个方法过大。例如:

/**
 * Saves the List of String[] to the File.
 * 
 * @param f
 * @param list
 * 
 * @throws IOException
 */
void saveList(File f, List<String[]> list) throws IOException {
    FileWriter fw = null;
    try {
        fw = new FileWriter(f);
        saveList(fw, list);
    } finally {
        if (null != fw) {
            // Ensure that fw is closed.
            fw.close();
        }
    }
}

/**
 * Saves the List of String[] to the Writer.
 * 
 * @param w
 * @param list
 * 
 * @throws IOException
 */
void saveList(Writer w, List<String[]> list) throws IOException {
    BufferedWriter bw = new BufferedWriter(w);
    for (int i = 0; i < list.size(); i++) {
        String[] dataEntry = list.get(i);
        for (int j = 0; j < dataEntry.length; j++) {
            bw.write("test1-2");
            // bw.append(dataEntry[j]+";");
        }
        bw.newLine();
    }
    bw.flush();
}

/**
 * Copies in's contents to out.
 * 
 * @param in
 *            Must not be null.
 * @param out
 *            Must not be null.
 * 
 * @throws IOException
 */
void copyStream(InputStream in, OutputStream out) throws IOException {
    if (null == in) {
        throw new NullPointerException("in must not be null");
    }
    if (null == out) {
        throw new NullPointerException("out must not be null");
    }
    byte[] buf = new byte[1024 * 8];
    int read = -1;
    while ((read = in.read(buf)) > -1) {
        out.write(buf, 0, read);
    }
}

/**
 * Copies in's contents to out, and ensures that in is closed afterwards.
 * 
 * @param in
 *            Must not be null.
 * @param out
 *            Must not be null.
 * 
 * @throws IOException
 */
void copyStreamAndCloseIn(InputStream in, OutputStream out) throws IOException {
    try {
        copyStream(in, out);
    } finally {
        in.close();
    }
}

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String filepath = getServletContext().getRealPath("\\") + "temp";
    String filename = "csv" + dateFormat.format(date) + ".csv";
    File file = new File(filepath + filename);
    file.createNewFile();

    saveList(file, list);

    long length = file.length();
    response.setContentType("text/csv");
    response.addHeader("Content-Disposition", "attachment; filename=" + filename);
    response.setContentLength((int) length);

    copyStreamAndCloseIn(new FileInputStream(file), response.getOutputStream());
}

至于奇怪的输出et-ts12et-ts12et-ts12ÿ,我不确定为什么会这样。

你是如何看待这个价值的?打印到控制台,然后读取文件?打印到控制台并在另一个编辑器中打开文件都会产生奇怪的结果,具体取决于使用的字符编码。