Java Byte Array Save to File nio writeBytes(final byte[] bytes, final OutputStream output)

Here you can find the source of writeBytes(final byte[] bytes, final OutputStream output)

Description

write Bytes

License

Apache License

Parameter

Parameter Description
bytes a parameter
output a parameter

Exception

Parameter Description
IOException an exception

Declaration

static void writeBytes(final byte[] bytes, final OutputStream output) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    /**//from   w ww .ja  v a 2  s .co m
     * @param bytes
     * @param output
     * @throws IOException
     */
    static void writeBytes(final byte[] bytes, final OutputStream output) throws IOException {
        try (final ByteArrayInputStream input = new ByteArrayInputStream(bytes)) {
            transfer(input, output);
        }
    }

    /**
     * @param input
     * @param output
     * @throws IOException
     */
    static void transfer(final InputStream input, final OutputStream output) throws IOException {
        final byte[] buffer = new byte[4096];
        while (true) {
            final int n = input.read(buffer);
            if (-1 == n) {
                return;
            }
            output.write(buffer, 0, n);
        }
    }

    /**
     * @param outputStream
     * @param string
     */
    static final void write(final OutputStream outputStream, final String string) throws IOException {
        write(outputStream, string.getBytes(DEFAULT_CHARSET));
    }

    /**
     * @param outputStream
     * @param data
     */
    static final void write(final OutputStream outputStream, final byte[] data) throws IOException {
        outputStream.write(data);
    }
}

Related

  1. fileWriteBytes(byte[] data, String file)
  2. writeHeader(File input, ByteArrayOutputStream headerStream)
  3. writeIntChars(int value, int index, byte[] buf)
  4. writeToBinaryFile(String filename, byte[] data)
  5. writeToFile(File file, byte[] content)