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

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

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

8条回答
  •  被撕碎了的回忆
    2020-12-08 09:44

    As of Java 1.7, there's a new way: java.nio.file.Files.write

    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey key = kgen.generateKey();
    byte[] encoded = key.getEncoded();
    Files.write(Paths.get("target-file"), encoded);
    

    Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:

    byte[] data = Files.readAllBytes(Paths.get("source-file"));
    

提交回复
热议问题