How can I write a byte array to a file in Java?

后端 未结 8 2054
野的像风
野的像风 2020-12-08 09:07

How to write a byte array to a file in Java?

相关标签:
8条回答
  • 2020-12-08 09:46
             File file = ...
             byte[] data = ...
             try{
                FileOutputStream fos = FileOutputStream(file);
                fos.write(data);
                fos.flush();
                fos.close();
             }catch(Exception e){
              }
    

    but if the bytes array length is more than 1024 you should use loop to write the data.

    0 讨论(0)
  • 2020-12-08 09:47

    A commenter asked "why use a third-party library for this?" The answer is that it's way too much of a pain to do it yourself. Here's an example of how to properly do the inverse operation of reading a byte array from a file (sorry, this is just the code I had readily available, and it's not like I want the asker to actually paste and use this code anyway):

    public static byte[] toByteArray(File file) throws IOException { 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 
       boolean threw = true; 
       InputStream in = new FileInputStream(file); 
       try { 
         byte[] buf = new byte[BUF_SIZE]; 
         long total = 0; 
         while (true) { 
           int r = in.read(buf); 
           if (r == -1) {
             break; 
           }
           out.write(buf, 0, r); 
         } 
         threw = false; 
       } finally { 
         try { 
           in.close(); 
         } catch (IOException e) { 
           if (threw) { 
             log.warn("IOException thrown while closing", e); 
           } else {
             throw e;
           } 
         } 
       } 
       return out.toByteArray(); 
     }
    

    Everyone ought to be thoroughly appalled by what a pain that is.

    Use Good Libraries. I, unsurprisingly, recommend Guava's Files.write(byte[], File).

    0 讨论(0)
提交回复
热议问题