2011-01-28 91 views
-2
import java.io.FileInputStream; 

import org.apache.commons.codec.binary.Base64; 


public class Encode 
{ 



public static String encodeFileStream(String filePath) throws Exception //file path ex : C:\Program Files\Cordys\Web\reports\I0001180.pdf 
{  

StringBuffer sb=new StringBuffer(); 

try 
{ 


    FileInputStream fin = new FileInputStream(filePath); 
    //StringBuffer sb=new StringBuffer(); 
    int lineLength = 72; 
    byte[] buf = new byte[lineLength/4*3]; 


    while (true) 
    { 
    int len = fin.read(buf); 
    if (len <= 0) 
    { 
     break; 
    } 

    //new Base64().encode(byte); 
    //sb.append(Base64.encode(buf)); 
    //sb.append(Base64.encodeBase64(buf)); 

    Base64 b = new Base64(); 
    sb.append(b.encode(buf)); 




    //return sb.toString(); 
    } 
} 

catch(Exception e) 
{ 
    return e.getMessage(); 
} 

return sb.toString(); 
} 

public static void main(String args[]) throws Exception 
{ 

    try 
    { 

     String s=""; 

    s=encodeFileStream("E:/CSSDocument/Test.pdf"); 
    } 

    catch(Exception e) 
    { 
      e.getMessage(); 
    } 

} 
} 
+0

@monika請清理你的代碼。 – 2011-01-28 05:00:53

回答

1

行後

s=encodeFileStream("E:/CSSDocument/Test.pdf"); 

添加

System.out.println(s); 

,並請清潔你的代碼:)

0

的一個原因,你不能看到任何輸出是你的程序沒有任何輸出。 main方法調用encodeFileStream來讀取和編碼文件,將結果賦給String變量s ...然後退出而不輸出它。

添加System.out.println(s);(或類似的東西)輸出編碼的文件內容。

其他景點:

  • 你的代碼是一個爛攤子。修復空白和縮進。
  • 方法encodeFileStream的命名很差。它所做的是編碼文件的內容......而不是「文件流」的內容。
  • 您的緩衝區長度可能太小......而PDF文件是二進制的,所以「行長度」的概念是沒有意義的。
  • 將代碼硬連線到代碼中可能不是必需的。
  • 您的程序會錯誤地(大部分時間)對文件的最後一個「緩衝區」進行編碼。提示:len可以是0buf.length以外的值。