By BoLOBOSE payday loan

Reading information from a binary file with java

This tutorial is an extension from “writing information to a binary file with java.” It is in your best interest to read the previous article since this one will be continuing the code.

Previously we created a bunch of primitive data types along with a string. These files have been written to the data file entitled “file.dat” If you did not want to follow the previous article you can download the article here along with the data file within it.

We are going to want to add more classes to import. The classes that we need to import are the “ObjectInputStream” and “FileInputStream.” You should now have the following classes imported into your file.

1
2
3
4
5
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

Since we have already written our data to the file and closed it we will need to open the file to read it using the input stream. Like in the last tutorial we are going to need to associate the memory to blank then try to load the file that we created earlier. The code will look something like this.

1
2
3
4
5
6
7
ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));
        }catch(IOException e){
            System.out.println("There was a problem opening the file: " + e);
            System.exit(0);
        }

The next thing to do is read the binary in the same order that it was written, top to bottom, so if we first write an integer then boolean we need to read an integer then a boolean or else we are going to get some wrong numbers coming back at us. The next part of the code is also in try catch using the Exception e.

Please note that it is good practice to place individual try catch whenever you read from the file and load into memory. This will allow you to better find errors but for the sake of this article we are going to save the space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try{
            byte var1 = inputStream.readByte();
            short var2 = inputStream.readShort();
            int var3 = inputStream.readInt();
            long var4 = inputStream.readLong();
 
            float var5 = inputStream.readFloat();
            double var6 = inputStream.readDouble();
 
            char var7 = inputStream.readChar();
            String var8 = inputStream.readUTF();
 
            boolean b1 = inputStream.readBoolean();
 
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }

If you would like to take a look at all of the code used in this demo it is placed below for your convenience.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* Code with Design
 *
 * Created By: Caleb Jonasson
 *
 * Desc: This class file is used to create a binary file,
 * write values to the file and check for errors along the way.
 */
 
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
 
public class writebin {
 
    public static void main(String[] args) {
        //the filename to create.
        String fileName = "file.dat";
 
        //creating the space in memory for the file
        ObjectOutputStream  outputStream = null;
 
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }
 
        byte foo = 1;
        short bar = 5;
        int baz = 543;
        long qurk = 123923892;
 
        float flt = 1;
        double dbl = 1.2323;
 
        char chr = 'a';
        String str = "hello";
 
        boolean bool = false;
 
        try{
            //integet based
            outputStream.writeByte(foo);
            outputStream.writeShort(bar);
            outputStream.writeInt(baz);
            outputStream.writeLong(qurk);
 
            //decimal based
            outputStream.writeFloat(flt);
            outputStream.writeDouble(dbl);
 
            //alpha based
            outputStream.writeChar(chr);
            outputStream.writeUTF(str);
 
            //true false based
            outputStream.writeBoolean(bool);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }
        System.out.println("Records have been written to the file.");
 
        ObjectInputStream inputStream = null;
        try{
            inputStream = new ObjectInputStream(new FileInputStream(fileName));
        }catch(IOException e){
            System.out.println("There was a problem opening the file: " + e);
            System.exit(0);
        }
        try{
            byte var1 = inputStream.readByte();
            short var2 = inputStream.readShort();
            int var3 = inputStream.readInt();
            long var4 = inputStream.readLong();
 
            float var5 = inputStream.readFloat();
            double var6 = inputStream.readDouble();
 
            char var7 = inputStream.readChar();
            String var8 = inputStream.readUTF();
 
            boolean b1 = inputStream.readBoolean();
 
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }
        System.out.println("Reading of the file: " + fileName + " has been completed.");
 
    }
 
}

Writing information to a binary file in java

In this tutorial I will be showing you how to import the required IO classes, check for errors using a try catch and write to a binary file. In order to do this tutorial a basic knowledge of Java, methods and variables is required.

Get the files used in this tutorial.

The first thing we need to do is import our classes. The classes we will import are going to be the following: “ObjectOutputStream”, “FileOutputStream” and the IOException.

1
2
3
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

The next thing that is required is to create the object “ObjectOutputStream.” We will do this by using the classes we imported at the start of this tutorial. We will also be placing this into a try catch statement to see if we are properly opening the file.

1
2
3
4
5
6
7
String fileName = "file.dat";
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }

Take note that we are getting the file name from the a string variable and using it in our new file stream.

Since we now have our file created and classes imported the next thing required is for us to create all of the variables we will be using in this example. Since I will be using all of the primitive variable types there will be a fair sized list you will need to type out.

1
2
3
4
5
6
7
8
9
10
11
12
byte foo = 1;
        short bar = 5;
        int baz = 543;
        long qurk = 123923892;
 
        float flt = 1;
        double dbl = 1.2323;
 
        char chr = 'a';
        String str = "hello";
 
        boolean bool = false;

The next step is to write all of the variables to the file through the output stream. Once again this will be done using try catch block but you shouldn’t have a problem if you follow along correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
try{
            //integet based
            outputStream.writeByte(foo);
            outputStream.writeShort(bar);
            outputStream.writeInt(baz);
            outputStream.writeLong(qurk);
 
            //decimal based
            outputStream.writeFloat(flt);
            outputStream.writeDouble(dbl);
 
            //alpha based
            outputStream.writeChar(chr);
            outputStream.writeUTF(str);
 
            //true false based
            outputStream.writeBoolean(bool);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }

The final piece of the code will close the output stream and tell us that we have successfully written to a file.

1
System.out.println("Records have been written to the file.");

The file with everything in it is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class writebin {
    public static void main(String[] args) {
        String fileName = "file.dat";
 
        ObjectOutputStream  outputStream = null;
 
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
        }catch(IOException e){
            System.out.println("Could not open the file." + e);
            System.exit(0);
        }
 
        byte foo = 1;
        short bar = 5;
        int baz = 543;
        long qurk = 123923892;
 
        float flt = 1;
        double dbl = 1.2323;
 
        char chr = 'a';
        String str = "hello";
 
        boolean bool = false;
 
        try{
            //integet based
            outputStream.writeByte(foo);
            outputStream.writeShort(bar);
            outputStream.writeInt(baz);
            outputStream.writeLong(qurk);
 
            //decimal based
            outputStream.writeFloat(flt);
            outputStream.writeDouble(dbl);
 
            //alpha based
            outputStream.writeChar(chr);
            outputStream.writeUTF(str);
 
            //true false based
            outputStream.writeBoolean(bool);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }
        System.out.println("Records have been written to the file.");
    }
 
}