2012-09-07 35 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");

相关问题