[英]Base64 decode in C# or Java
我有一个Base64编码的对象与以下标题:
application/x-xfdl;content-encoding="asc-gzip"
解码对象的最佳方法是什么? 我需要剥离第一行吗? 另外,如果我把它变成一个字节数组(byte []),我该怎么解压缩呢?
谢谢!
我想我最初错过了。 通过说标题是
application/x-xfdl;content-encoding="asc-gzip"
我的意思是这是文件的第一行。 因此,为了使用Java或C#库来解码文件,是否需要删除此行?
如果是这样,剥离第一行的最简单方法是什么?
要在C#中解码Base64内容,可以使用Convert Class静态方法 。
byte[] bytes = Convert.FromBase64String(base64Data);
您还可以使用GZipStream类来帮助处理GZip流。
另一个选择是SharpZipLib 。 这将允许您从压缩数据中提取原始数据。
在Java中,您可以使用Apache Commons Base64类
String decodedString = new String(Base64.decodeBase64(encodedBytes));
我能够使用以下代码将.xfdl文档转换为Java DOM文档。
我使用iHarder的 Base64实用程序来执行Base64解码。
private static final String FILE_HEADER_BLOCK =
"application/vnd.xfdl;content-encoding=\"base64-gzip\"";
public static Document OpenXFDL(String inputFile)
throws IOException,
ParserConfigurationException,
SAXException
{
try{
//create file object
File f = new File(inputFile);
if(!f.exists()) {
throw new IOException("Specified File could not be found!");
}
//open file stream from file
FileInputStream fis = new FileInputStream(inputFile);
//Skip past the MIME header
fis.skip(FILE_HEADER_BLOCK.length());
//Decompress from base 64
Base64.InputStream bis = new Base64.InputStream(fis,
Base64.DECODE);
//UnZIP the resulting stream
GZIPInputStream gis = new GZIPInputStream(bis);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(gis);
gis.close();
bis.close();
fis.close();
return doc;
}
catch (ParserConfigurationException pce) {
throw new ParserConfigurationException("Error parsing XFDL from file.");
}
catch (SAXException saxe) {
throw new SAXException("Error parsing XFDL into XML Document.");
}
}
仍在努力成功修改和重新编码文档。
希望这可以帮助。
听起来你正在处理gzip和Base 64编码的数据。 剥离任何mime标头后,应该使用Apache commons codec之类的东西将Base64数据转换为字节数组。 然后,您可以将byte []包装在ByteArrayInputStream
对象中,并将其传递给GZipInputStream
,以便您读取未压缩的数据。
对于java,您是否尝试过java内置的java.util.zip包? 或者,Apache Commons有Commons Compress库来处理zip,tar和其他压缩文件类型。 至于解码Base 64,有几个开源库,或者你可以使用Sun的sun.misc.BASE64Decoder类。
从其他地方复制,对于Base64我链接到commons-codec-1.6.jar:
public static String decode(String input) throws Exception {
byte[] bytes = Base64.decodeBase64(input);
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new ByteArrayInputStream(bytes))));
StringBuffer buffer = new StringBuffer();
char[] charBuffer = new char[1024];
while(in.read(charBuffer) != -1) {
buffer.append(charBuffer);
}
return buffer.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.