Java中文件与字节数组转换
2024-10-10 07:11:16
注:来源于JavaEye
文件转化为字节数组:
http://www.javaeye.com/topic/304980
- /**
- * 文件转化为字节数组
- *
- * @param file
- * @return
- */
- public static byte[] getBytesFromFile(File file) {
- byte[] ret = null;
- try {
- if (file == null) {
- // log.error("helper:the file is null!");
- return null;
- }
- FileInputStream in = new FileInputStream(file);
- ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
- byte[] b = new byte[4096];
- int n;
- while ((n = in.read(b)) != -1) {
- out.write(b, 0, n);
- }
- in.close();
- out.close();
- ret = out.toByteArray();
- } catch (IOException e) {
- // log.error("helper:get bytes from file process error!");
- e.printStackTrace();
- }
- return ret;
- }
字节数组转化为文件
http://www.javaeye.com/topic/304982
- /**
- * 把字节数组保存为一个文件
- *
- * @param b
- * @param outputFile
- * @return
- */
- public static File getFileFromBytes(byte[] b, String outputFile) {
- File ret = null;
- BufferedOutputStream stream = null;
- try {
- ret = new File(outputFile);
- FileOutputStream fstream = new FileOutputStream(ret);
- stream = new BufferedOutputStream(fstream);
- stream.write(b);
- } catch (Exception e) {
- // log.error("helper:get file from byte process error!");
- e.printStackTrace();
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- // log.error("helper:get file from byte process error!");
- e.printStackTrace();
- }
- }
- }
- return ret;
- }
最新文章
- .NET Core中ADO.NET SqlClient的使用与常见问题
- 深入浅出 Redis client/server交互流程
- CSS生僻问题一网打尽
- css2----兼容----ie67的3像素bug
- Projects\Portal_Content\Indexer\CiFiles文件夹下文件占用磁盘空间过大问题。
- EasyUi – 4.datagrid
- 【转】appStore上传苹果应用程序软件发布流程
- Java基础-String、StringBuffer、StringBuilder
- Servlet的生命周期及filter,servletRequest和servletResponse
- 深入理解javascript的闭包
- 修改 jquery easyui 表单验证默认的样式
- 第04讲- Android项目目录结构分析
- scp命令报错(IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!)
- vs 2015常用快捷键
- js表白心形特效
- 10分钟快速入门Redis
- java中带图片按钮的大小设置
- Android Studio 删除多余的虚拟设备(Virtual Device)
- 注意:Tomcat Get请求的坑!
- 基于OpenGL编写一个简易的2D渲染框架-03 渲染基本几何图形
热门文章
- 禁用quartz自动检查更新
- 在Mac上搭建Python虚拟环境
- Getting Started with Django Rest Framework and AngularJS
- u-boot界面添加命令[demo]
- AspNet Core 发布到Linux系统和发布IIS 注意项
- HDU 3001 Travelling(状态压缩DP+三进制)
- POJ 3616 Milking Time(最大递增子序列变形)
- csu 1553(RMQ+尺取法)
- Hive2.x 版本的安装及配置 以及要注意的事项
- java 用maven 构建项目时@Override错误的解决办法