2012-09-07 32 views
1

在Windows下面的程序輸出的不同與Unix系統。 您能否向我解釋爲什麼會發生這種情況,以及如何在Unix和Windows上使這種行爲保持一致。BASE64Encoder結果不同,從窗口到unix

因爲我使用的Unix的文件的編碼,它不可能給它在Windows系統上進行解碼。

在這方面的任何幫助,將不勝感激。提前致謝。

import sun.misc.BASE64Encoder; 
import sun.misc.CharacterEncoder; 

public class TestEncode { 

public static void main(String[] args) {   

     byte signature[] = "[35, 44, -31, 18, 78, 84, -113, 1, 27, 36, -79, -60, 75, -14, -80, -99, 65, 11, -45, -54, 23, -100, 74, -54, -26, -77, 33, -40, 104, 90, -33, 32, -123, -76, -27, -118, -25, -97, -85, 22, -64, 102, -7, 119, -65, 35, -114, 31, -83, 73, -57, 63, -7, 47, -31, 48, 28, -109, 54, -90, -24, -21, -102, 59, 82, -14, -52, -77, -22, -25, -15, -81, 70, 52, -42, 93, 76, -51, 96, 87, 29, -37, -40, -71, -121, 44, -44, 74, 23, -76, 29, 108, -56, 48, 46, -26, -73, -53, 90, 53, 25, -96, 115, -79, 93, -128, -46, -119, -30, 22, -107, -27, 6, -120, 2, 19, -72, -5, 30, -54, -34, 26, -22, -44, 93, 40, 84, -125]".getBytes(); 

    byte encodedSignature[] = null; 

     CharacterEncoder encoder; 
     encoder = new BASE64Encoder(); 
     encodedSignature = encoder.encode(signature).getBytes(); 


     System.out.println(encodedSignature.length); 

} 

} 
+0

這看起來像Java指定它在getBytes()方法。這兩個系統上使用的是什麼版本的jvm? – count0

+1

也請分享您在每個環境中獲得的結果。 –

回答

1

你可以試試這個和你有什麼結果的Windows VS Linux操作系統:

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; 
import com.sun.org.apache.xml.internal.security.utils.Base64; 
import java.io.IOException; 

public class Base64Test { 

    public static void main(String args[]) throws IOException, Base64DecodingException { 
     String orig = "original String before base64 encoding in Java"; 

     //encoding byte array into base 64 
     String encoded = Base64.encode(orig.getBytes("UTF-8"));//make sure the bytes are utf-8 and not platform default  

     System.out.println("Original String: " + orig); 
     System.out.println("Base64 Encoded String : " + new String(encoded,"UTF-8"));//ensure string is utf-8 

     //decoding byte array into base64 
     byte[] decoded = Base64.decode(encoded);  
     System.out.println("Base 64 Decoded String : " + new String(decoded,"UTF-8"));//ensure string is utf-8 

    } 
} 

煤礦是(僅Windows):

原始字符串:的base64前原字符串用Java編碼

Base64編碼字符串:b3JpZ2luYWwgU3RyaW5nIGJlZm9yZSBiYXNlNjQgZW5jb2RpbmcgaW4gSmF2YQ ==

Base64編碼解碼的字符串:base64編碼前原字符串中的Java

,你可能會面臨的問題是:

  • 默認情況下在Windows上使用的字符編碼不同的是,一個上Linux操作系統。特別是因爲getBytes()是涉及也許將其設置爲您自己的默認像getBytes("UTF-8")(在我的例子中,我試圖做到這一點)
  • 它可能是由行分隔符默認爲(「\ r \ n」)和(「\ n「)。

,但我不能肯定

3

你可能在使用的每臺機器上不同的字符集。試試這個,找出:

System.out.println("Default Charset=" + Charset.defaultCharset()); 

我調用getBytes()方法時懷疑你的問題。默認情況下,它使用平臺的默認字符集。如果你想保證它使用相同的一個,通過調用getBytes("UTF-8");

相關問題