Ввод формы написания сервлетов Java в CSV - PullRequest
1 голос
/ 20 февраля 2012

Я пытаюсь создать сервлет, который анализирует входные данные формы и создает из них файл .csv, но объект 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();     
        }          
}

Извините, если код немного слабоват. Мой текущий вывод при записи строки «test1-2» для каждой записи

е-ts12et-ts12et-ts12ÿ

Буду признателен за любые дальнейшие комментарии к самому коду. Я просто экспериментирую с вещами, которые я нахожу в сети, у меня нет реальных рекомендаций.

1 Ответ

1 голос
/ 20 февраля 2012

Возможно, я бы добавил несколько методов, чтобы ни один из них не был слишком большим. Например:

/**
 * 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ÿ, я не уверен, почему это будет.

Как вы смотрите это значение? Печать на консоль, чтение файла потом? Как печать в консоли, так и открытие файла в другом редакторе могут привести к странным результатам в зависимости от используемой кодировки символов.

...