1、File 转成 byte[]
public static byte[] getImageStream(String imageUrl,
HttpServletRequest request) {
ServletContext application = request.getSession().getServletContext();
String url = application.getRealPath("/")+imageUrl;
byte[] buffer = null;
File file = new File(url);
FileInputStream fis;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
if(file.exists()) {
file.delete();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
2、byte[] 转成 File
public static void readBin2Image(byte[] byteArray, String targetPath) {
InputStream in = new ByteArrayInputStream(byteArray);
File file = new File(targetPath);
String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
if (!file.exists()) {
new File(path).mkdir();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}