Java. Byte streams. Classes DataInputStream, DataOutputStream, FileInputStream, FileOutputStream. Examples of using

Byte streams. Classes DataInputStream, DataOutputStream, FileInputStream, FileOutputStream. Examples of using

This topic demonstrates the use of Java language tools for working with byte streams. Examples of common tasks for the solution of which are used are the classes DataInputStream, DataOutputStream, FileInputStream, FileOutputStream.


Contents


Search other websites:




1. Writing and reading a one-dimensional array of type int[] in a byte file stream. Example

Let a one-dimensional array of the int[] type be given, which is needed:

  • write to a byte file stream;
  • read from byte file stream.

To solve this problem classes are well suited:

  • DataInputStream – an input stream that contains methods for reading data from standard Java types to which the int type belongs;
  • DataOutputStream – an output stream that contains methods for writing data of standard types defined in Java;
  • FileInputStream – an input stream that contains methods that read data from a file;
  • FileOutputStream – An output stream that contains methods that write data to a file.

To organize data writing to a file, you need:

  • create a file stream of type FileOutputStream;
  • place the created file stream in the DataOutputStream constructor;
  • use the methods of the DataOutputStream class to write data to a file.

To organize the reading of data from a file you need:

  • create a file stream of type FileInputStream;
  • place the newly created file stream into the DataInputStream constructor;
  • use the methods of the DataInputStream class to read data from a file.

Example.

import java.io.*;

...

public static void main(String[] args) throws IOException
{
  // The source data is some array of integers
  int[] arrInt = { 2, 5, -1, 100, 33 };

  // 1. Write arrInt array to byte file "integers.bin"
  // 1.1. Create a file byte stream associated with the name "integers.bin"
  FileOutputStream fs = new FileOutputStream("integers.bin");

  // 1.2. Create a byte stream containing methods for reading primitive data types
  DataOutputStream ds = new DataOutputStream(fs);

  // 1.3. Write the number of elements in an array - use the write() method
  ds.writeInt(arrInt.length);

  // 1.4. Write an array of integers
  for (int i=0; i<arrInt.length; i++)
    ds.writeInt((int)arrInt[i]);

  // 1.5. Close the file "integers.bin"
  fs.close();

  // -------------------------------------------------------------------
  // 2. Read an array of integers from the byte file "integers.bin"
  int[] arrInt2; // an array into which data will be read from the file "integers.bin"

  // 2.1. Create a file stream associated with the name "integers.bin"
  FileInputStream fs2 = new FileInputStream("integers.bin");

  // 2.2. Create data stream associated with fs2 file stream
  DataInputStream ds2 = new DataInputStream(fs2);

  // 2.3. Read the number of integer elements that are written in the file
  int count = ds2.readInt();

  // 2.4. Allocate memory fo array arrInt2
  arrInt2 = new int[count];

  // 2.5. The cycle of reading data from ds2 and copying them to the arrInt2 array
  for (int i=0; i<arrInt2.length; i++)
    arrInt2[i] = ds2.readInt();

  // 2.6. Close the stream ds2
  ds2.close();

  // ------------------------------------------------------------------
  // 3. Display array arrInt2
  System.out.println("Array arrInt2: ");
  for (int i=0; i<arrInt2.length; i++)
    System.out.println(arrInt2[i]);
}

The result of the program

Array arrInt2:
2
5
-1
100
33

 

2. Writing and reading data of different types (double, int, char). Example

Let it be necessary:

  • write to the file sequentially the values of variables of the double, int, char types;
  • read the value of variables of types double, int, char.

 

import java.io.*;

...

public static void main(String[] args) throws IOException
{
  // Initial data - double, int, char values

  // 1. Write data
  // 1.1. Create a file byte stream associated with the name "data.bin"
  FileOutputStream fs = new FileOutputStream("data.bin");

  // 1.2. Create a byte stream containing methods for reading primitive data types
  DataOutputStream ds = new DataOutputStream(fs);

  // 1.3. Write the number of type double
  ds.writeDouble(5.85);

  // 1.4. Write the number of type int
  ds.writeInt(2000);

  // 1.5. Write character of type char
  ds.writeChar('Z');

  // 1.6. Close the file "data.bin"
  fs.close();

  // -------------------------------------------------------------------
  // 2. Read data from the byte file "data.bin" into variables doubleData, intData, charData
  double doubleData;
  int intData;
  char charData;

  // 2.1. Create a file stream that is associated with the name "data.bin"
  FileInputStream fs2 = new FileInputStream("data.bin");

  // 2.2. Create data stream associated with fs2 file stream
  DataInputStream ds2 = new DataInputStream(fs2);

  // 2.3. Read the number of type double
  doubleData = ds2.readDouble();

  // 2.4. Read the number of type int
  intData = ds2.readInt();

  // 2.5. Read the number of type char
  charData = ds2.readChar();

  // 2.6. Close the stream ds2
  ds2.close();

  // -------------------------------------------------------------------
  // 3. Display data
  System.out.println("doubleData = " + doubleData);
  System.out.println("intData = " + intData);
  System.out.println("charData = " + charData);
}

The program result

doubleData = 5.85
intData = 2000
charData = Z

 

3. Writing and reading an array of real numbers in a byte file. Example

In the example, first an array of doubles is written to the file, then this array is read into the internal data structures and displayed. The classes FileOutputStream, DataOutputStream, FileInputStream, DataInputStream are used.

import java.io.*;

...

public static void main(String[] args) throws IOException
{
  // Writing an array of real numbers to a byte file

  // 1. Prepare an array of real numbers AD
  double AD[] = new double[5];
  for (int i=0; i<AD.length; i++)
    AD[i] = i*2.5 + 1;

  // 2. Create an instance of class FileOutputStream
  FileOutputStream fOut = new FileOutputStream("array.bin");

  // 3. Use the DataOutputStream class to output to a file
  DataOutputStream dOut = new DataOutputStream(fOut);

  // 4. Writing array data to a byte file
  // 4.1. First you need to write the number of elements in the array
  dOut.writeInt(AD.length);

  // 4.2. Loop of array writing to the file
  for (int i=0; i<AD.length; i++)
    dOut.writeDouble(AD[i]);

  // 5. Close the stream dOut
  dOut.close();

  // 6. Print the AD array to the console
  System.out.println("Array AD:");
  for (int i=0; i<AD.length; i++)
    System.out.println(AD[i]);

  // ----------------------------------
  // Reading real numbers from a file into an AD2[] array

  // 7. Declare the resulting array
  double AD2[];

  // 8. Create the instance of file FileInputStream
  FileInputStream fIn = new FileInputStream("array.bin");

  // 9. Create an instance of the DataInputStream class and associate it with the fIn file
  DataInputStream dIn = new DataInputStream(fIn);

  // 10. Read the number of numbers in the array
  int count;
  count = dIn.readInt();

  // 11. Allocate memory for array AD2[]
  AD2 = new double[count];

  // 12. Read numbers from file into AD2[] array
  for (int i=0; i<AD2.length; i++)
    AD2[i] = dIn.readDouble();

  // 13. Close the stream DataInputStream
  dIn.close();

  // 14. Display the array AD2[]
  System.out.println("\nArray AD2:");

  for (int i=0; i<AD2.length; i++)
    System.out.println(AD2[i]);
}

The result of the program

Array AD:
1.0
3.5
6.0
8.5
11.0

Array AD2:
1.0
3.5
6.0
8.5
11.0

 

4. Example of copying files using a byte stream

The example provides a code snippet that copies files. The tools of the FileInputStream and FileOutputStream classes are used.

import java.io.*;

...

public static void main(String[] args) throws IOException
{
  // Copying files.
  // File "inputFile.txt" is copied to the file "outputFile.txt"
  FileInputStream fi = null;
  FileOutputStream fo = null;

  try {
    // Attempt to open files
    fi = new FileInputStream("inputFile.txt"); // исходный файл
    fo = new FileOutputStream("outputFile.txt"); // результирующий файл

    // Copy cycle
    int d;

    do {
      // read bytes from fi
      d = fi.read();

      // write bytes to fo
      if (d != -1)
        fo.write(d);
    } while (d != -1);

    System.out.println("Ok!");
  }
  catch (IOException e) {
    // If one of the files is not open, then display a message
    System.out.println("I/O error: " + e);
  }
  finally {
    try {
      // If the first file is open, then close it
      if (fi != null)
        fi.close();
    }
    catch (IOException e2) {
      System.out.println("Cannot close file \"inputFile.txt\"");
    }

    try {
      // If another file is open, close it.
      if (fo != null)
        fo.close();
    }
    catch (IOException e2) {
      System.out.println("Cannot close file \"outputFile.txt\"");
    }
  }
}

 


Related topics

 


 

0
fb-share-icon20