2012-02-21 33 views
1

我有一個允許上傳二進制文件的web應用程序。我必須解析它們並將內容1:1保存到字符串中,然後保存到數據庫中。使用FileItemStream在Java中處理二進制文件

當我在unix機器上使用uuencode對二進制文件進行編碼時,它就可以工作。有沒有辦法在java中自動執行此操作?

if (isMultipart) { 

      //Create a new file upload handler 
      ServletFileUpload upload = new ServletFileUpload(); 

      //Parse the request 
      FileItemIterator iter = upload.getItemIterator(request); 

      while (iter.hasNext()) { 
       FileItemStream item = iter.next(); 
       String name = item.getFieldName(); 

       InputStream stream = item.openStream(); 

       if (!item.isFormField()) { 

        BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 
        String line; 
        licenseString = ""; 

        while ((line = reader.readLine()) != null) { 
         System.out.println(line); 

         // Generate License File 
         licenseString += line + "\n"; 
        } 
       } 
      } 
      session.setAttribute("licenseFile", licenseString); 
      System.out.println("adding licensestring to session. "); 
     } 

它當然適用於所有上傳的非二進制文件。我如何擴展它以支持二進制文件?

回答

3
// save to file 
// ======================================= 
InputStream is = new BufferedInputStream(item.openStream()); 
BufferedOutputStream output = null; 

try { 
    output = new BufferedOutputStream(new FileOutputStream("temp.txt", false)); 
    int data = -1; 
    while ((data = is.read()) != -1) { 
     output.write(data); 
    } 
} finally { 
    is.close(); 
    output.close(); 
} 

// read content of file 
// ======================================= 
System.out.println("content of file:"); 
try { 
    FileInputStream fstream = new FileInputStream("temp.txt"); 

    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    String line; 

    licenseString = ""; 
    String strLine; 
    while ((strLine = br.readLine()) != null) { 
      System.out.println(javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes())); 
      licenseString += javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()) + "\n"; 
    }           
} catch (Exception e) { 
    System.err.println("Error: " + e.getMessage()); 
} 
0

一個更好的辦法是將上傳寫入到一個臨時文件,然後從那裏處理:

if (!item.isFormField()) { 

    InputStream stream = new BufferedInputStream(item.getInputStream()); 
    BufferedOutputStream output = null; 

    try { 
     output = new BufferedOutputStream(new FileOutputStream(your_temp_file, false)); 
     int data = -1; 
     while ((data = input.read()) != -1) { 
      output.write(data); 
     } 
    } finally { 
     input.close(); 
     output.close(); 
    } 
} 

現在你有一個臨時文件,這是一樣的上傳的文件,你可以做你的'其他'計算。

+0

謝謝,這是一個很好的輸入,但我已經試過了。它不能解決我的「編碼」 - 問題:( – doonot 2012-02-21 10:42:49