2011-12-28 110 views
2

我写在Spring MVC文件上传和我使用的编码文件为Base64字符串发送到Web服务:如何将Java中Base64编码的文件解码为原始内容?

org.apache.commons.codec.binary.Base64; 
String encoded = Base64.encodeBase64String(uploadItem.getFileData().getBytes()); 

Web服务将编码字符串发回给我,我想知道如何从编码字符串中重新生成文件。我知道你可以这样做:

byte[] decoded = Base64.decodeBase64(encoded); 

但你如何将字节数组更改回文件?

+0

你能详细说明吗?这个文件在哪里?你想发送一个HTTP响应? – 2011-12-28 15:52:05

+0

我并不关心它在哪里以及它如何被发送。我只是想知道如何处理编码的字符串,当我从Web服务获取它。 – Saliceran 2011-12-28 16:29:48

回答

4

你可以使用FileOutputStreamthis example写字节的文件。

+0

谢谢。那正是我想要做的。 – Saliceran 2011-12-28 16:32:21

+2

请注意,示例代码可能会泄漏文件句柄,因为它不会在finally块中关闭。 – McDowell 2011-12-28 19:31:35

4

使用FileOutputStream

//Java 7 
try (OutputStream out = new FileOutputStream(file)) { 
    out.write(decoded); 
} 
+0

我正在使用Java 6. – Saliceran 2011-12-28 16:30:03