Table of Contents

Byte Array to File

Classic Way

    public static void main(String[] args) {
        byte[] b = "ABCDEFGHIJK".getBytes();
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("./out.txt");
            fileOutputStream.write(b);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException ignored) {
                    //DO NOT CARE...
                }
            }
        }
    }

Better Way Since Java 1.7 with try(resource){}

We do not have to close the resource, Java will handle it for us.

    public static void main(String[] args) {
        byte[] b = "ABCDEFGHIJK".getBytes();
        try (FileOutputStream fileOutputStream = new FileOutputStream("./out.txt")) {
            fileOutputStream.write(b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }