Java binary file format

Запись данных в двоичный файл на Java

Компьютеры с двоичными файлами основаны на двоичной системе нумерации, которая состоит всего из tw… С тегом java, обработка файлов, двоичный файл.

Двоичные файлы

Компьютеры основаны на двоичной системе нумерации, которая состоит всего из двух уникальных чисел, 0 и 1 . Все операции, которые возможны в десятичной системе счисления (сложение, вычитание, умножение, деление), одинаково возможны и в двоичной системе счисления. Двоичный файл доступен для чтения компьютером, но не для чтения человеком. Все исполняемые программы хранятся в двоичных файлах, как и большинство файлов числовых данных. Напротив, текстовые файлы хранятся в форме (обычно ASCII), которая удобочитаема для человека.

Запись данных в Двоичный файл

Прием значений данных с консоли и отправка их из буфера памяти на дополнительное запоминающее устройство. Он имеет дело со всеми типами примитивных данных, а именно. short, int, long, float, double, char, boolean и String. В этой системе данные хранятся в байтах на вторичных устройствах хранения. При создании двоичного файла выполните следующие действия: 1. Создайте файл в режиме выходного потока вместе с объектом потока.

Читайте также:  Java iso 8601 timestamp

Синтаксис: FileOutputStream FileOutputStream Например,

FileOutputStream fout = new FileOutputStream("example.dat");

Расширение имени файла (.dat) обозначает тип данных, которые хранятся в режиме выходного потока на жестком диске.

2. Создайте связь между объектом FileOutputStream и выходным потоком буфера.

Синтаксис: DataOutputStream DataOutputStream(объект FileOutputStream); Например:

DataOutputStream dout = new DataOutputStream(fout);

3. Примите необходимые данные из консоли одним из двух способов: (a) С помощью streamreader путем импорта java.io . * (b) Использование класса Scanner путем импорта java.util. *

4. Запишите данные во вторичное хранилище с помощью этих команд:

  • Для записи коротких данных введите – .writeShort
  • Для записи данных целочисленного типа – .writeInt
  • Для записи длинных данных введите – .writeLong
  • Для записи данных типа float – .writeFloat
  • Для записи данных двойного типа – переменной> переменной>
  • Для записи данных символьного типа – .writeChar
  • Для записи данных строкового типа – .writeUTF

( UTF расшифровывается как Преобразованный в Юникод формат строка)

5. Закройте файл данных, используя объект FileOutputStream как:

Примерная программа

Электронный магазин хочет провести инвентаризацию всех типов товаров в двоичном файле “inventory.dat” для ввода названия продукта, кода продукта, количества продукта и цены. Ниже приведена программа для создания двоичного файла для выполнения вышеуказанной задачи.

import java.io.*; public class sample < public static void main(String args[]) throws IOException < BufferedReader ob=new BufferedReader(new InputStreamReader(System.in)); // Creating binary file FileOutputStream fout=new FileOutputStream("inventory.dat"); DataOutputStream dout=new DataOutputStream(fout); int n, q, pr; String str, pc; System.out.println("Enter number of products:"); n=Integer.parseInt(ob.readLine()); for(int i=1;i<=n;i++) < System.out.println("Enter product name"); str=ob.readLine(); System.out.println("Enter product code"); pc=ob.readLine(); System.out.println("Enter product quantity"); q=Integer.parseInt(ob.readLine()); System.out.println("Enter price"); pr=Integer.parseInt(ob.readLine()); // Writing data values from memory to binary file dout.writeUTF(str); dout.writeUTF(pc); dout.writeInt(q); dout.writeInt(pr); >// Closing binary file object fout.close(); dout.close(); ob.close(); > >

Читайте ещё по теме:

Источник

Working with binary files

In raw binary format, numerical data transfer is more faster than and compact than as text characters.

Writing Binary File

In the below example ,Firstly we create some data arrays containing some arbitrary values. After that we create object of FileOutputStream to open a stream to a file. We wrap this stream object with an instance of the DataOutputStream class, which contains writeInt (int i) and the writeDouble (double d) methods, to write the data to the file as pairs of int/double type values. It also contains many useful methods for writing primitive types of the writeX() form, where X indicates a primitive type.

import java.io.*; import java.util.*; public class BinaryFileWrite < public static void main(String arg[]) < Random ran = new Random(); // Create an integer array and a double array. int[] i_data = new int[15]; double[] d_data = new double[15]; // and fill them for (int i = 0; i < i_data.length; i++) < i_data[i] = i; d_data[i] = ran.nextDouble() * 10.0; >File file = null; // Get the output file name from the argument line. if (arg.length > 0) file = new File(arg[0]); // or use a default file name if (file == null) < System.out.println("Default: numerical.dat"); file = new File("numerical.dat"); >// Now write the data array to the file. try < // Create an output stream to the file. FileOutputStream file_output = new FileOutputStream(file); // Wrap the FileOutputStream with a DataOutputStream DataOutputStream data_out = new DataOutputStream(file_output); // Write the data to the file in an integer/double pair for (int i = 0; i < i_data.length; i++) < data_out.writeInt(i_data[i]); data_out.writeDouble(d_data[i]); >// Close file when finished with it.. file_output.close(); > catch (IOException e) < System.out.println("IO exception background-color:black">  C:\Program Files\Java\jdk1.6.0_18\bin>java BinaryFileWrite 
Default: numerical.dat

Reading Binary File

In this example, firstly , we create some data arrays containing some arbitrary values. After that we create object of FileOutputStream class to open a stream to a file. We wrap this stream object with an instance of the DataOutputStream class, which contains writeInt (int i) and the writeDouble (double d) methods, to write the data to the file as pairs of int/double type values. It also contains many useful methods for writing primitive types of the writeX( ) form, where X indicates a primitive type.

Example :

import java.io.*; public class BinaryFileRead < public static void main(String arg[]) < File file = null; int i_data = 0; double d_data = 0.0; // Get the file from the argument line. if (arg.length >0) file = new File(arg[0]); if (file == null) < System.out.println("Default: numerical.dat"); file = new File("numerical.dat"); >try < // Wrap the FileInputStream with a DataInputStream FileInputStream file_input = new FileInputStream(file); DataInputStream data_in = new DataInputStream(file_input); while (true) < try < i_data = data_in.readInt(); d_data = data_in.readDouble(); >catch (EOFException eof) < System.out.println("End of File"); break; >// Print out the integer, double data pairs. System.out.printf("%3d. Data = %8.3e %n", i_data, d_data); > data_in.close(); > catch (IOException e) < System.out.println("IO Exception =: " + e); >> // main >
C:\Program Files\Java\jdk1.6.0_18\bin>java BinaryFileRead
Default: numerical.dat
0. Data = 9.418e+00
1. Data = 1.611e+00
2. Data = 6.298e+00
3. Data = 5.124e+00
4. Data = 2.766e-01
5. Data = 7.026e+00
6. Data = 8.160e+00
7. Data = 3.438e+00
8. Data = 1.587e+00
9. Data = 4.521e+00
10. Data = 4.027e-01
11. Data = 7.058e-01
12. Data = 3.245e+00
13. Data = 8.602e+00
14. Data = 8.451e+00
End of File

Источник

How to Read and Write Binary Files in Java

In this Java File IO tutorial, we show you how to read and write binary files using both legacy File I/O API and new File I/O API (NIO). The legacy API (classes in the java.io.* package) is perfect for manipulating low-level binary I/O operations such as reading and writing exactly one byte at a time, whereas the NIO API (classes in the java.nio.* package) is more convenient for reading and writing the whole file at once, and of course, faster than the old File I/O API.

1. Understanding Byte Streams

We use byte streams to read and write data in binary format, exactly 8-bit bytes. All byte stream classes are descended from the abstract classes InputStream and OutputStream . The following class diagram depicts the main classes in the legacy File I/O API that are designed for working with binary files:

Byte Streams API

You can notice that these classes implement the AutoCloseable interface, which means that we can use the try-with-resources structure to close these streams automatically.

At the top of the hierarchy, the abstract class InputStream defines two primary methods for reading bytes from an input stream:

  • read() : reads one byte of data, returns the byte as an integer value. Return -1 if the end of the file is reached.
  • read(byte[]) : reads a chunk of bytes to the specified byte array, up to the size of the array. This method returns -1 if there’s no more data or the end of the file is reached.

Similarly, the abstract class OutputStream defines two primary methods for writing bytes to an output stream:

  • write(int) : writes the specified byte to the output stream.
  • write(byte[]) : writes the specified array of bytes to the output stream.

Moving down, the implementation classes FileInputStream and FileOutputStream are for reading and writing streams of raw bytes, one or multiple bytes at a time. Whereas the BufferedInputStream and BufferedOutputStream are more efficient by buffering the input stream and output stream to reduce the number of calls to the native API.

Now, let’s see some code examples.

2. Reading and Writing Binary Files Using FileInputStream and FileOutputStream

The following examples use the FileInputStream and FileOutputStream classes to perform low level binary I/O.

This program copies one file to another, one byte at a time. The source file and destination file are provided from command line’s arguments:

import java.io.*; /** * Copy one file to another using low level byte streams, one byte at a time. * @author www.codejava.net */ public class CopyFiles < public static void main(String[] args) < if (args.length < 2) < System.out.println("Please provide input and output files"); System.exit(0); >String inputFile = args[0]; String outputFile = args[1]; try ( InputStream inputStream = new FileInputStream(inputFile); OutputStream outputStream = new FileOutputStream(outputFile); ) < int byteRead = -1; while ((byteRead = inputStream.read()) != -1) < outputStream.write(byteRead); >> catch (IOException ex) < ex.printStackTrace(); >> >
java CopyFiles Project.zip Project1(1).zip

And the following program runs faster because it reads the whole input file into an array of bytes and then write the whole array of bytes to the output file:

import java.io.*; /** * Copy one file to another using low level byte streams, * read and write a whole.at once. * @author www.codejava.net */ public class CopyFilesOne < public static void main(String[] args) < if (args.length < 2) < System.out.println("Please provide input and output files"); System.exit(0); >String inputFile = args[0]; String outputFile = args[1]; try ( InputStream inputStream = new FileInputStream(inputFile); OutputStream outputStream = new FileOutputStream(outputFile); ) < long fileSize = new File(inputFile).length(); byte[] allBytes = new byte[(int) fileSize]; int bytesRead = inputStream.read(allBytes); outputStream.write(allBytes, 0, bytesRead); >catch (IOException ex) < ex.printStackTrace(); >> >

And the following program runs much faster by copying a chunk of bytes at a time (exactly 4096 bytes at a time):

import java.io.*; /** * Copy one file to another using low level byte streams, 4KB at a time. * @author www.codejava.net */ public class CopyFilesChunk < private static final int BUFFER_SIZE = 4096; // 4KB public static void main(String[] args) < if (args.length < 2) < System.out.println("Please provide input and output files"); System.exit(0); >String inputFile = args[0]; String outputFile = args[1]; try ( InputStream inputStream = new FileInputStream(inputFile); OutputStream outputStream = new FileOutputStream(outputFile); ) < byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) < outputStream.write(buffer, 0, bytesRead); >> catch (IOException ex) < ex.printStackTrace(); >> >

The following program reads the first 8 bytes of a file to identify if it is a PNG image format or not:

import java.io.*; /** * This program checks whether a file is of PNG image format or not, * by analysing its first 8 bytes. * @author www.codejava.net */ public class CheckPNG < private static int[] pngSignature = ; public static void main(String[] args) < if (args.length < 1) < System.out.println("Please provide the input file"); System.exit(0); >String inputFile = args[0]; try ( InputStream inputStream = new FileInputStream(inputFile); ) < int[] headerBytes = new int[8]; boolean isPNG = true; for (int i = 0; i < 8; i++) < headerBytes[i] = inputStream.read(); if (headerBytes[i] != pngSignature[i]) < isPNG = false; break; >> System.out.println("Is PNG file? " + isPNG); > catch (IOException ex) < ex.printStackTrace(); >> >

As you can see, using FileInputStream and FileOutputStream is really good for low level binary I/O such as analyzing a file or even create your own file format.

3. Reading and Writing Binary Files Using BufferedInputStream and BufferedOutputStream

Using BufferedInputStream and BufferedOutputStream is as same as FileInputStream and FileOutputStream . The only difference is that a buffered stream uses an array of byte internally to buffer the input and output to reduce the number of calls to the native API, hence increasing IO performance.

By default, both BufferedInputStream and BufferedOutputStream has an internal buffer of 8192 bytes (8KB), but we can specify a custom buffer size at initialization.

All the above examples can be re-written using buffered streams just by changing the instantiation of the streams. Here’s an example:

try ( InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile)); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); ) < byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) < outputStream.write(buffer, 0, bytesRead); >> catch (IOException ex)

int bufferSize = 16384; // 16KB buffer size InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile), bufferSize); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile), bufferSize);

4. Reading and Writing Binary Files Using New File I/O API (NIO)

The utility class Files in the java.nio.file package provides the following methods for reading and writing binary data:

  • readAllBytes(Path path) : reads all bytes from a file and returns an array of bytes. This method is intended for reading small files, not large ones.
  • write(Path path, byte[] bytes, OpenOption. options) : writes an array of bytes to a file with some useful options like CREATE, TRUNCATE_EXISTING, WRITE and APPEND.

Let’s see an example. The files copy program above can be re-written using NIO API like this:

import java.io.*; import java.nio.file.*; /** * Copy one file to another using low level byte streams, one byte at a time. * @author www.codejava.net */ public class CopyFilesNIO < public static void main(String[] args) < if (args.length < 2) < System.out.println("Please provide input and output files"); System.exit(0); >String inputFile = args[0]; String outputFile = args[1]; try < long start = System.currentTimeMillis(); byte[] allBytes = Files.readAllBytes(Paths.get(inputFile)); Files.write(Paths.get(outputFile), allBytes); long end = System.currentTimeMillis(); System.out.println("Copied in " + (end - start) + " ms"); >catch (IOException ex) < ex.printStackTrace(); >> >

Try to run this program and compare the time with the ones using legacy File I/O (on big files) you will see NIO performs much faster.

API References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Оцените статью