object、byte[]、File文件相互转换

您所在的位置:网站首页 byte转成file object、byte[]、File文件相互转换

object、byte[]、File文件相互转换

2023-09-26 06:55| 来源: 网络整理| 查看: 265

object转换File文件

上一篇写了一个《RestTemplate浅谈》,因为跨服务调用接口,接口返回是一个JSON字符串,里面有带一个文件,但是文件类型是一个byte[]数组,而JSONObject拿出来的却是object类型的,那么怎么转呢,查了一下资料。总结如下:

object类转换成file文件时,需要注意,不能直接转,需要转换。 object转换成byte[]数组,再由byte[]数组转换成File文件写进文件夹。

还有两点需要注意:

1、Object 对象必须是可序列化对象 。 2、可序列化的 Object 对象都可以转换为一个磁盘文件;反过来则不一定成立,只有序列 化文件才可以转换为 Object 对象。

话不多说,直接上代码:

object转byte[]数组

/** * TODO 从对象获取一个字节数组 * @param obj 必须是可序列化的 * @return */ public byte[] getBytesByObject(Serializable serializableObject ) throws Exception { if (serializableObject == null) { return null; } ByteArrayOutputStream byteArrayOutputStream= new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(serializableObject ); return byteArrayOutputStream.toByteArray(); }

byte[]转File文件,写进指定路径,并返回改文件

/** * TODO 把字节数组保存为一个文件 * @param b * @param outputFile * @return */ public File getFileFromBytes(byte[] b, String outputFile) { BufferedOutputStream stream = null; File file = null; try { //获取本地文件 file = new File(outputFile); //打开输出流 FileOutputStream fstream = new FileOutputStream(file); //字节缓冲输出流 stream = new BufferedOutputStream(fstream); //开始写数据 stream.write(b); } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; }

byte[]数组转object类型

/** * TODO 把字节数组转换成object类型 * @param bytes * @param outputFile * @return */ public static Object getObjectByBytes(byte[] bytes) throws Exception { if (bytes== null || bytes.length == 0){ return null; } ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); return objectInputStream.readObject(); }

File文件转byte[]数组

/** * TODO 把文件转换成字节数组 * @param b * @param outputFile * @return */ public static byte[] getBytesFromFile(File file) { if (file == null) { return null; } try { FileInputStream stream = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = stream.read(b)) != -1) { out.write(b, 0, n); } stream.close(); out.close(); return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; }

以上就是object、byte[]、file文件之间的相互转换类,直接可以使用,根据大家的不同需求可对里面的返回值和传参进行修改,制作不易,不喜勿喷,小白一枚正在进阶,大佬请留情😁😁😉



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3