Java 文件和字节数组相互转换

  1. 文件转成字节数组
	/**
	 * 文件转换成字节数组
	 * @param path 文件路径
	 * @return 字节数组
	 */
	public static byte[] fileToBytes(String path) {
		InputStream is = null;
		try {
			is = new FileInputStream(path);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			byte[] buffer = new byte[4096];
			int bytesRead = -1;
			while ((bytesRead = is.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.flush();
			return os.toByteArray();
		} catch (Exception e) {
			log.error("文件转换成字节数组报错:" + path, e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
  1. 字节数组转成文件
	/**
	 * 字节数组转换成文件
	 * @param bytes 字节数组
	 * @param path 文件路径
	 * @return 文件
	 */
	public static File bytesToFile(byte[] bytes, String path) {
		File file = new File(path);
		try {
			// 导入 Spring 核心包 spring-core
			FileCopyUtils.copy(bytes, file);
		} catch (IOException e) {
			throw new RuntimeException("字节数组转换成文件有误", e);
		}
		return file;
	}
posted @ 2023-02-16 10:18  君子键  阅读(213)  评论(0)    收藏  举报