Writing binary files

An efficient way of writing binary files is by using BufferedOutputStream. For example, writing a byte[] to a file can be accomplished as follows:

final byte[] buffer...;
Path classFile = Paths.get(
"build/classes/modern/challenge/Main.class");

try (BufferedOutputStream bos = newBufferedOutputStream(
Files.newOutputStream(classFile, StandardOpenOption.CREATE,
StandardOpenOption.WRITE))) {

bos.write(buffer);
}
If you're writing byte by byte, use the write(int b) method, and, if you're writing a chunk of data, use the write​(byte[] b, int off, int len) method.

A very handy method for writing a byte[] to a file is Files.write​(Path path, byte[] bytes, OpenOption... options). For example, let's write the content of the preceding buffer:

Path classFile = Paths.get(
"build/classes/modern/challenge/Main.class");

Files.write(classFile, buffer,
StandardOpenOption.CREATE, StandardOpenOption.WRITE);

Writing a binary file via MappedByteBuffer can be accomplished as follows (this can be useful for writing huge text files):

Path classFile = Paths.get(
"build/classes/modern/challenge/Main.class");
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(
classFile, EnumSet.of(StandardOpenOption.CREATE,
StandardOpenOption.READ, StandardOpenOption.WRITE))) {

MappedByteBuffer mbBuffer = fileChannel
.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length);

if (mbBuffer != null) {
mbBuffer.put(buffer);
}
}

Finally, if we are writing a certain piece of data (not raw binary data), then we can rely on DataOutputStream. This class comes with writeFoo() methods for different kinds of data. For example, let's write several floats into a file:

Path floatFile = Paths.get("float.bin");

try (DataOutputStream dis = new DataOutputStream(
new BufferedOutputStream(Files.newOutputStream(floatFile)))) {
dis.writeFloat(23.56f);
dis.writeFloat(2.516f);
dis.writeFloat(56.123f);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset