• java File和Byte[]数组 相互转换


    1. public class Test {
    2. public static void main(String[] args){
    3. String filePath = "E:\softoon\workspace_softoon\TestMobile\src\1.docx";
    4. String outFilePath = "E:\softoon\workspace_softoon\TestMobile\src";
    5. String outFileName = "2.docx";
    6. getFile(getBytes(filePath),outFilePath,outFileName);
    7. }
    8. // ----------------获得指定文件的byte数组 ----------------
    9. public static byte[] getBytes(String filePath){
    10. byte[] buffer = null;
    11. try {
    12. File file = new File(filePath);
    13. FileInputStream fis = new FileInputStream(file);
    14. ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
    15. byte[] b = new byte[1000];
    16. int n;
    17. while ((n = fis.read(b)) != -1) {
    18. bos.write(b, 0, n);
    19. }
    20. fis.close();
    21. bos.close();
    22. buffer = bos.toByteArray();
    23. } catch (FileNotFoundException e) {
    24. e.printStackTrace();
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. return buffer;
    29. }
    30. // ----------------根据byte数组,生成文件 ----------------
    31. public static void getFile(byte[] bfile, String filePath,String fileName) {
    32. BufferedOutputStream bos = null;
    33. FileOutputStream fos = null;
    34. File file = null;
    35. try {
    36. File dir = new File(filePath);
    37. if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
    38. dir.mkdirs();
    39. }
    40. file = new File(filePath+"\"+fileName);
    41. fos = new FileOutputStream(file);
    42. bos = new BufferedOutputStream(fos);
    43. bos.write(bfile);
    44. } catch (Exception e) {
    45. e.printStackTrace();
    46. } finally {
    47. if (bos != null) {
    48. try {
    49. bos.close();
    50. } catch (IOException e1) {
    51. e1.printStackTrace();
    52. }
    53. }
    54. if (fos != null) {
    55. try {
    56. fos.close();
    57. } catch (IOException e1) {
    58. e1.printStackTrace();
    59. }
    60. }
    61. }
    62. }
    63. }


  • 相关阅读:
    webGL 光照
    Go语言入门之指针的使用
    Go语言入门之变量声明
    服务器开启防火墙
    Linux安全之密钥登录
    Mysql优化之my.cnf参数优化
    程序员工作法
    laravel中新增路由文件
    Mysql用户管理(远程连接、授权)
    Laravel通过Swoole提升性能
  • 原文地址:https://www.cnblogs.com/edgedance/p/6979944.html
Copyright © 2020-2023  润新知