Writing and reading objects and arrays to a binary file with java

This article requires that you have read the following java tutorials or you feel comfortable writing and reading variables to a binary file.

Advantage of writing files in binary with java

Reading information from a binary file with java

Writing information to a binary file with java

The first thing that is needed in this tutorial is an object that we are going to save into binary. This object is going to be a simple object with one instance variable, two constructors, one of which is default and a get name method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.Serializable;
public class Person implements Serializable{
    private String name;
 
    public Person(){
        name = "no name";
    }
    public Person(String x){
        name = x;
    }
    public String getName(){
        return name;
    }
}

You may notice that at the top of our new object we have a line that says “import java.io.Serializable” This line imports a class that we can use. It is required when we want to turn an object into binary and save it to a file. There is also a line that implements Serializable. This line is needed so the class can use the methods within the class Serializable.

The next piece of code will be added outside of the main method. It is added because we will need to use the file input and output streams along with the object input and output streams. We will also be using an IOException. If you would like to use other exception handling classes you can certainly feel free too. I would advise using the file not found and end of file exception.

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

This next bit of code is going to save what we want for a filename inside of a string variable. After that we will be creating two person objects and two arrays, one being a string type and the other an integer type. The next line of code will create a null output stream then create the output stream while testing it for any errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//the filename to create.
        String fileName = "file.dat";
 
        //Person Objects
        Person p1 = new Person("Bob");
        Person p2 = new Person("Paul");
 
        //Array to write
        String[] helloThere = new String[]{"dog","cat","hamburger"};
        int[] thereHello = new int[]{1,2,3,4,5,6,7,8,9};
 
        //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);
        }

Writing the objects to a binary file is done in a similar way to writing everything else. Since an array is actually an object it uses the same method as the object person. To write these two kinds of objects we will need to use the try catch in order to handle any errors then inside of that write objects using the outputstream.

1
2
3
4
5
6
7
8
9
10
11
12
try{
            outputStream.writeObject(p1);
            outputStream.writeObject(p2);
            outputStream.writeObject(helloThere);
            outputStream.writeObject(thereHello);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }

Now that we are done writing the objects to the binary file we will need to read the information back into new objects.

We are going to create a new input stream in the same way that we made the output stream. It will first be of type null and then we will truly create it inside of the try catch blocks.

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

Since we are going to pull the information out of the file and reload them as objects we will need to create new objects in memory to show that we have successfully read the file.

1
2
3
4
5
//Create new blank objects to store the data in.
        Person newp1 = null;
        Person newp2 = null;
        String[] test = null;
        int[] test2 = null;

In order to read the information we will rely on our trusted try and catch blocks to let us test that everything is going as planned. Inside of the try catch blocks there is going to be the code required to load the objects read from memory into the new objects that we created in the code above.

You will also notice that when we saved the object information to a new object we specified what kind of object it was. This casts the information and sets it up as said object so it can once again use the methods that come along with that object type.

1
2
3
4
5
6
7
8
9
10
try{
            newp1 = (Person)inputStream.readObject();
            newp2 = (Person)inputStream.readObject();
            test = (String[])inputStream.readObject();
            test2 = (int[])inputStream.readObject();
            inputStream.close();
        }catch(Exception e){
            System.out.println("There was an issue reading from the file: " + e);
            System.exit(0);
        }

The last thing required is for us to do is test a person and an array. We will do this as follows.

1
2
System.out.println("newp1\'s name is " + newp1.getName());
        System.out.println(test2[0]);

If everything goes according to plan then we will have no errors. If you do have an error then please refer to the last bit of code to see if you did anything wrong.

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
/* 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";
 
        //Person Objects
        Person p1 = new Person("Bob");
        Person p2 = new Person("Paul");
 
        //Array to write
        String[] helloThere = new String[]{"dog","cat","hamburger"};
        int[] thereHello = new int[]{1,2,3,4,5,6,7,8,9};
 
        //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);
        }
 
 
 
        try{
            outputStream.writeObject(p1);
            outputStream.writeObject(p2);
            outputStream.writeObject(helloThere);
            outputStream.writeObject(thereHello);
 
            outputStream.close();
 
        }catch(IOException e){
            System.out.println("Writing error: " + e);
            System.exit(0);
        }
        System.out.println("Records have been written to the file.");
 
 
        /*Reading the objects from memory.*/
 
        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);
        }
 
        //Create new blank objects to store the data in.
        Person newp1 = null;
        Person newp2 = null;
        String[] test = null;
        int[] test2 = null;
 
        try{
            newp1 = (Person)inputStream.readObject();
            newp2 = (Person)inputStream.readObject();
            test = (String[])inputStream.readObject();
            test2 = (int[])inputStream.readObject();
            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.");
 
        //Now we test to make sure that it worked correctly.
        System.out.println("newp1\'s name is " + newp1.getName());
        System.out.println(test2[0]);
 
    }
 
}

Random Images Using A PHP Function: cj_random_image

Recently while working on a new blog layout for Code With Design I found myself finding that the code blocks look far to dull. My way of fixing this was to add an image but it didn’t end up helping anything, the image just looked repetitive and thus it is time to find some change and include a random image setup for each block.

WordPress uses a while loop to display the post information. I plan on taking advantage of this by adding a style to each of the div blocks. This will force the function to load for each div block and thus making the background images random for each individual block.

If the image was entered into the css then each block would look the same:

Function loads -> CSS is put into the style sheet -> style sheet loads into each element.

If the image was loaded on each div individually then the process will look something like this:

Function loads inside of div tag -> CSS is put into the looping div -> On each run the Function runs its random -> The random is placed out on each div.

The function loads a list of URL paths separated by comas. Then you are given the option of using placement properties and two of them so bottom right or top left is aloud. The final variable that this function uses is the repeat. This allows you to repeat the image by x, y, repeat or no-repeat.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
//'/images/br_corner_cloud.png,/images/tr_corner_cloud.png','bottom','right','no-repeat'
//creating a function
function cj_random_image($image_array, $prop1, $prop2, $repeat) {
//image arrays
$image_array = explode(",",$image_array);
 
$image_max = count($image_array);
//random image count based on user input
$image_rando = mt_rand(1, $image_max) - 1;
 
//image
echo 'url('.$image_array[$image_rando].')'.$prop1.' '.$prop2.' '.$repeat;
}
//created by calebj
?>

The first thing the function does is takes what the user has placed into it then outputs it. The main inputs are the URL paths. These paths are counted and the count is used as the maximum on the random. This forces the mt_rand function to return the proper value which means that you can enter any amount of image URLs and the function will still work out.

In order to use this effectively you will need to place the function like so:

1
2
3
<div style="background: #f2f2f2<?php cj_random_image('images/br_corner_cloud.png,images/cloud1.png','bottom','right','no-repeat'); ?> ">
 
</div>

If you would like to see this code working in action please click here. Keep in mind that you need to refresh the page to see the random clouds show up.

Looping with an array

Recently while working on a search engine I needed to return what the user had searched for, separate the words into an array by the spaces then use a for loop to output the array content 1 by 1. The following code looks as follows.

$loader_keywords = $_POST['keyword'];
$keywords = explode(‘ ‘,$loader_keywords);
echo ‘<p>’;
for ($a = 0; $a < count($keywords); $a++) {
echo “$keywords[$a]” . ‘ ‘;
}
echo ‘</p>’;

Stepping Through The Code

$loader_keywords = $_POST['keyword'];

The first line (above) takes what the user has entered from the previous page and loads the content into a variable. Now we have something to work with.

$keywords = explode(‘ ‘,$loader_keywords);

The second line loads the variable $keywords from the explode function. This function takes the variable $loader_keywords and separates the content by the spaces. These spaces are stripped and the input words are loaded into an array. If the user searches for “happy bunny kittens” Then we will have an array that looks like this.

$keywords[1] = “happy”
$keywords[2] = “bunny”
$keywords[3] = “kittens”

The follow line has the single purpose of separating the array values into paragraphs.

echo ‘<p>’;

Now we are going to create a for loop to display the contents of the $keywords array.

for ($a = 0; $a < count($keywords); $a++) {
echo “$keywords[$a]” . ‘ ‘;
}

Now you can see that the we are having keywords outputted but the $a variable increased each time the loops is played through. You will also see that the loops limit is based on how how many keywords there are. This is counted using the very simple count function.

The rest of the code is used to close off the paragraph tags.

$loader_keywords = $_POST['keyword'];