文件转Byte[]、以及byte[]转文件的工具类

╰半橙微兮° 2022-05-09 13:46 385阅读 0赞

一、
1.文件转Byte[]:

  1. // 第1步、使用File类找到一个文件
  2. File f= new File("e:/demo/demoNext" + File.separator + "java.docx") ; // 声明File对象
  3. // 第2步、通过子类实例化父类对象
  4. InputStream input = null ; // 准备好一个输入的对象
  5. input = new FileInputStream(f) ; // 通过对象多态性,进行实例化
  6. // 第3步、进行读操作
  7. byte result[] = new byte[1024] ; // 所有的内容都读到此数组之中
  8. input.read(result) ; // 读取内容 网络编程中 read 方法会阻塞
  9. // 第4步、关闭输出流
  10. input.close() ; // 关闭输出流
  11. System.out.println("内容为:" + result);

2.文件转Byte[]的工具类:

  1. public class fileUtil {
  2. //将文件转换成Byte数组
  3. public static byte[] getBytesByFile(String pathStr) {
  4. File file = new File(pathStr);
  5. try {
  6. FileInputStream fis = new FileInputStream(file);
  7. ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
  8. byte[] b = new byte[1024];
  9. int n;
  10. while ((n = fis.read(b)) != -1) {
  11. bos.write(b, 0, n);
  12. }
  13. fis.close();
  14. byte[] data = bos.toByteArray();
  15. bos.close();
  16. return data;
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. return null;
  21. }
  22. }

测试类调用:

  1. String pathStr="e:/demo/demoNext/java.docx";
  2. System.out.println("文件转byte:"+fileUtil.getBytesByFile(pathStr));

二、byte[]转文件的工具类:

  1. public class fileUtil {
  2. //将Byte数组转换成文件
  3. public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
  4. BufferedOutputStream bos = null;
  5. FileOutputStream fos = null;
  6. File file = null;
  7. try {
  8. File dir = new File(filePath);
  9. if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
  10. dir.mkdirs();
  11. }
  12. file = new File(filePath + "\\" + fileName);
  13. fos = new FileOutputStream(file);
  14. bos = new BufferedOutputStream(fos);
  15. bos.write(bytes);
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. } finally {
  19. if (bos != null) {
  20. try {
  21. bos.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. if (fos != null) {
  27. try {
  28. fos.close();
  29. } catch (IOException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. }
  35. }

测试类调用:

  1. //要生成文件的路径
  2. String filePath="e:/demo";
  3. //要生成文件的名字
  4. String fileName="java.docx";
  5. //result:byte[]
  6. fileUtil.getFileByBytes(result, filePath, fileName);

发表评论

表情:
评论列表 (有 0 条评论,385人围观)

还没有评论,来说两句吧...

相关阅读