2012-02-20 68 views
1

我想構建一個解析表單輸入並從它們創建一個.csv文件的servlet,但是bufferedWriter對象因爲沒有(對我來說)截斷很多字符的原因。Java Servlet寫入CSV格式的輸入

 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」字符串時,電流輸出爲

等-ts12et-ts12et-ts12ÿ

代碼本身任何進一步的評論,將不勝感激,我只是嘗試與我在網上找到的東西,我沒有實際的最佳做法的參考點。

回答

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ÿ,我不知道爲什麼會這樣。

您如何查看此值?打印到控制檯,然後閱讀文件?打印到控制檯並在另一個編輯器中打開文件可能會產生奇怪的結果,具體取決於使用的字符編碼。

+0

該文件從servlet發送到客戶端。我曾嘗試用leafpad,openOffice或Gnumeric打開它,每次都得到相同的結果。編碼問題在應用程序中非常重要,所以它確保輸入採用UTF-8格式,參數以UTF-8解析。但測試文本應該排除這一點(或者我認爲?) – 2012-02-20 18:01:59

+0

所以你說這是接收不正確字符編碼的CSV文本的客戶端,而不是文件('文件')被錯誤地保存?在這種情況下,您應該設置輸出的字符編碼。 'response.setContentType(「text/csv; charset = UTF-8」)'。 – 2012-02-20 18:06:19

+0

我不知道什麼改變了,但我組織的代碼,它實際上工作。 – 2012-02-21 10:28:32