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.

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

PHP: Increasing a scripts runtime

Often when working with long php scripts you may need more time then is aloud. Recently when working with lirkr search engine I came across a problem where the server would time me out due to the script taking so long. The reason this was taking so long is because I had to read information from pages and load it into the search engines database word by word and check if the word already exists.

Here is a simple way to change the duration of time a script is aloud to be executed for.

1
2
3
<?php
ini_set(max_execution_time, "300");
?>

Be careful when using this script. If your code lasts longer then a few minutes then chances are the code is not very efficient, you have a infinite loop somewhere or you could just be working with a database that not a lot of people will ever have to use.

JQuery: Show and hide images

In this tutorial we will be using JQuery to show and hide images that are displayed in our web page. If you would like to use the files used in this tutorial you can click here to download them.

When using JQuery the first thing that is required is for us to link to the JQuery library. The link to this library is contained within the header tags of the web page and look like this:

1
2
3
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

The next part of this code that is required is for us to create the functions that the buttons will link to. When the user presses one of these buttons the image will go into that state unless already in that state. It does this by using an “on click” that linking to the javascript function.

1
2
3
4
5
6
7
8
<script>
function showImage(){
	$('#imgSwitch').show();
}
function hideImage(){
	$('#imgSwitch').hide();
}
</script>

Now we need to create the img tags and give the image an ID that will work with the functions we have just created. The code for this looks like so:

1
<img id="imgSwitch" src="cjdesign.png">

The final part of code that is required is the form that links to the functions we created in the second group of javascript code. For this section of code we will be creating two buttons that will allow the change in image.

1
2
3
4
<form>
	<input type="button" value="show" onclick="showImage()"></input>
	<input type="button" value="hide" onclick="hideImage()"></input>
</form>

And finally this is what all of the code looks like together. The code you have created should look like this:

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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<head>
		<title>Show and Hide Images</title>
		<script src="http://code.jquery.com/jquery-latest.js"></script>
		<script>
			function showImage(){
				$('#imgSwitch').show();
			}
			function hideImage(){
				$('#imgSwitch').hide();
			}
		</script>
	</head>
	<body>
		<h1>Showing and Hiding Images</h1>
		<p>This is an example of showing and hiding images.</p>
		<img id="imgSwitch" src="cjdesign.png">
		<form>
			<input type="button" value="show" onclick="showImage()"></input>
			<input type="button" value="hide" onclick="hideImage()"></input>
		</form>
 
	</body>
</html>

Java: Tutorial about Arrays vs Static Arrays

This is a tutorial found on dream in code that I recently stumbled upon. It gives you a good look at an alternative to an array when using anything over java JDK 5. The tutorial covers some of the built in methods that the the ArrayList class comes with. It also goes over sorting, looping, checking for null and changing index’.

The tutorial was written by one of the moderators who goes by the screen name Locke.

You can find the tutorial here.

Update: Colours and code viewer

The colours and the code viewer has been updated to show lines and syntax highlighting. The updates have been set on March 28th at 10:48pm. The updates will be complete within the next week. The reason for the added length is purely because there are a lot of posts with a lot of code that need to be gone through. Another update post will follow this once everything has been completed.

The reason for the colour change is simple; the site needed a little blue.