Java中File与byte[]的互转方式
作者:看你家猫
这篇文章主要介绍了Java中File与byte[]的互转方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Java File与byte[]互转
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(); } } } }
Java byte数组转换成0和1的二进制
可以使用以下代码将Java中的byte数组转换为0和1的二进制字符串:
byte[] bytes = ...; StringBuilder binary = new StringBuilder(); for (byte b : bytes) { int val = b; for (int i = 0; i < 8; i++) { binary.append((val & 128) == 0 ? 0 : 1); val <<= 1; } } System.out.println(binary.toStri
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。