公司要求把xml以及jar文件上传到数据库,所以需要先把文件转成二进制,然后保存到数据库。需要使用时,再把二进制转成文件下载下来。
现在遇到的问题是,下载的xml文件中,有很多[null]或者空格。下载的jar文件,无法打开。
经过排查,是上传时,文件转二进制文件的时候,byte数组设置的大小不合适,应修改如下:
/**
* 文件转二进制
*/
private static byte[] file2Byte(File file) {
InputStream is = null;
ByteArrayOutputStream bos = null;
try {
is = new FileInputStream(file);
bos = new ByteArrayOutputStream();
// 注意数组大小, 之前写的是 2048,出现空格,修改成is.available(),空格消失
// byte[] bytes = new byte[2048];
byte[] bytes = new byte[is.available()];
while (is.read(bytes) != -1) {
bos.write(bytes);
}
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();