java:byte_to_file

Action disabled: revisions

Byte Array to File

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

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();
        }
    }
  • java/byte_to_file.txt
  • Last modified: 2020/06/15 11:50
  • by chongtin