java file and byte[] arrays are converted to each other

Source: Internet
Author: User

  
  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. }


java file and byte[] arrays are converted to each other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.