Advantages to writing files in binary with java

There are quite a few reasons that a programmer would like to write to a file in binary but the main reasons are speed, space and precision. Along with those three it is also important to understand when you are going to want to write in binary and when not to.

Speed is a great advantage to writing to files in binary. It allows you to simply pull the information that you want and load it into variables and objects effectively and easily. As you would try to do the same with its counter part you would instead have to go through each line, looping and parsing the information as you go which is not the most effective way to read a file. Using the methods that come with the ObjectOutputStream you can simply write “writeInt(variableInt);” and the data will be written to the file in binary.

The second great advantage to writing is binary is the space. Your files will be much more compact when everything is saved in binary and this makes an especially large difference when you have to pull large amounts of information from a file. Since everything is made up of a set amount of bytes you can compress more into one file by not having any white space.

The third reason to why binary is a good alternative is the precision of writing what is in memory to the file. There is no parsing, the files are written and pulled as they once where when they were placed in memory at one point in time. This allows for less of a risk factor for your programs to stop working on a client and will allow you to have more trust in what you are pulling out of a saved file.

There are times that you will want to write to a file using the full print writer over binary and this is when you have something like a crash log that allows a user to read what happened when the program crashed, where the bug was etc. Aside from information you want to be seen the upside of binary is quite significant. It allows you to have your own set pattern as to writing and pulling information making it harder for someone to go into your file and know what they are changing. And example of this would be a video game. You don’t want someone able to simple log in and change his or her score. You would be better off if they were unable to read the file.

Keeping information secretive is a great part about binary files. Sure you can crack it using patterns but it is less likely a general user will be able to do so unless they know how the program was written.

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.");
    }
 
}