Showing posts with label example. Show all posts
Showing posts with label example. Show all posts

Friday, May 20, 2011

Your Own Java Classes

To use Java effectively, you want to create and use your own classes. This is one of the great powers of object-oriented languages--the ability to construct programs out of independent building-blocks that cut large problems down into small, easily solvable ones. There's a lot more that can be said, and much of it is elsewhere. So I'll get right into a very simple, very basic example here.

We're going to create a very simple object class that will print a "Hello" message to the screen when called. This class will have two different methods that will do the same thing, though we'll vary the messages they print a bit so that we can see which one is doing the work.

Here's our class: (download HelloClass.Java)

public class HelloClass{

/**
* sayHello() prints "Hello!" to the Java console output.
*/
public void sayHello(){
System.out.println("Hello!\n");
}

/**
* doHello() prints "Hello, hello!" to the Java console output.
* It's static, so you don't need to instatiate a HelloClass
* object to use it.
*/
public static void doHello(){
System.out.println("Hello, hello!\n");
}

} // End of HelloClass


The two methods we have to print messages are sayHello() and doHello(). To use sayHello(), we need to have a HelloClass object created, then call that object's sayHello() method.

doHello(), however, is a static method. This means is belongs to the class, not to any object of the class. So we can use it without any HelloClass objects being created first.

Here's a class that uses these methods as described: (download UseHello.java)

public class UseHello{
public static void main(String[] arg){

// We can use doHello() without a HelloClass object:
HelloClass.doHello(); // call the HelloClass's doHello() method.

// But we need to create a HelloClass object to use sayHello():
HelloClass hello=new HelloClass();
hello.sayHello(); // call hello's sayHello() method.

}
} // End of UseHello.


If we try to call sayHello() without first creating a HelloClass object, like this:
HelloClass.sayHello();

then we'll get the dreaded "calling a non-static method from a static context" error message. That's letting you know that you need to instantiate (or create) a HelloClass object first, then tell that object to call its method.

Static methods are useful for things like general arithmetic and calculation or other methods that might be used in a way where state information is unimportant. But beware, it's easy to create static methods when what's really wanted is an object that does what you want.

Files available for download through: http://saundby.com/beginwithjava/.
StumbleUpon

Thursday, April 14, 2011

Java File Save and File Load: Objects

Jump to Reading Data from Files with Java>>

Saving Data to Files with Java


Saving objects to a file in Java has a few steps to it, but it's pretty easy. We open a file to write to, create a "stream" for putting objects into the file, write the objects to that stream to put them in the file, then close the stream and file when we're done.

To reiterate:

1. Open a file.

2. Open an object stream to the file.

3. Write the objects to that stream.

4. Close the stream and file.

1. Opening the File
To open a file for writing, we use a FileOutputStream object. When we construct the new FileOutputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, it creates a new file. To keep things simple, we're not going to check for a file existing here, or anything like that.

Example:
FileOutputStream saveFile = new FileOutputStream("saveFile.sav");

2. Open an Object Stream
To write objects to the FileOutputStream, we create an ObjectOutputStream. We give it the FileOutputStream object we've set up when we construct the new ObjectOutputStream object.

Example:
ObjectOutputStream save = ObjectOutputStream(saveFile);

3. Write Objects
When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.

Example:
save.writeObject(objectToSave);

4. Close Up
When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.

Example:
save.close();

Example Program:
import java.io.*;
import java.util.ArrayList;

public class SaveObjects{

public static void main(String[] arg){

// Create some data objects for us to save.
boolean powerSwitch=true;
int x=9, y=150, z= 675;
String name="Galormadron", setting="on", plant="rutabaga";
ArrayList stuff = new ArrayList();
stuff.add("One");
stuff.add("Two");
stuff.add("Three");
stuff.add("Four");
stuff.add("Five");

try{  // Catch errors in I/O if necessary.
// Open a file to write to, named SavedObj.sav.
FileOutputStream saveFile=new FileOutputStream("SaveObj.sav");

// Create an ObjectOutputStream to put objects into save file.
ObjectOutputStream save = new ObjectOutputStream(saveFile);

// Now we do the save.
save.writeObject(powerSwitch);
save.writeObject(x);
save.writeObject(y);
save.writeObject(z);
save.writeObject(name);
save.writeObject(setting);
save.writeObject(plant);
save.writeObject(stuff);

// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace(); // If there was an error, print the info.
}
}
}

Reading Data Files with Java


Now we need to know how to get data back from a file with Java. Since the data objects were stored using an ObjectOutputStream, they are saved in a way that makes them easy to read back using an ObjectInputStream.

There's one problem with ObjectImputStream, however. It doesn't return objects of the specific classes that they were originally. It just returns generic Objects. To get things back into their original class, we have to cast them into that type. Usually that means we need to know what their class was when they were written. It's possible to save class information along with the data, but in this case we just assume that we're reading back a file we have written, so we already know what class everything should be. I'll go into the details of reading other files in another article.

The steps are practically the same as for writing objects to a file:

1. Open a file.

2. Open an object stream from the file.

3. Read the objects to that stream.

4. Close the stream and file.

1. Opening the File
To open a file for reading, we use a FileInputStream object. When we construct the new FileIntputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, we get an error which will print out a nastygram when we get to our catch statement. To keep things simple, we're not going to check for a file existing here.

Example:
FileInputStream saveFile = new FileInputStream("saveFile.sav");

2. Open an Object Stream
To read objects to the FileInputStream, we create an ObjectInputStream. We give it the FileInputStream object we've set up when we construct the new ObjectInputStream.

Example:
ObjectInputStream restore = ObjectInputStream(saveFile);

3. Read Objects
When we read objects from the ObjectInputStream, it gets then from the file.

Example:
Object obj = restore.readObject();

3 and a half. Cast Back to Class
Step 3. only restores a generic Object. If we know the original class, we should cast the Object back to its original class when we read it. If we had stored a String object, we'd read it something like this:
String name = (String) restore.readObject();

4. Close Up
When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.

Example:
restore.close();

Here's an example program to read back information saved by the first example program:
import java.io.*;
import java.util.ArrayList;

public class RestoreObjects{

public static void main(String[] arg){

// Create the data objects for us to restore.
boolean powerSwitch=false;
int x=0, y=0, z=0;
String name="", setting="", plant="";
ArrayList stuff = new ArrayList();

// Wrap all in a try/catch block to trap I/O errors.
try{
// Open file to read from, named SavedObj.sav.
FileInputStream saveFile = new FileInputStream("SaveObj.sav");

// Create an ObjectInputStream to get objects from save file.
ObjectInputStream save = new ObjectInputStream(saveFile);

// Now we do the restore.
// readObject() returns a generic Object, we cast those back
// into their original class type.
// For primitive types, use the corresponding reference class.
powerSwitch = (Boolean) save.readObject();
x = (Integer) save.readObject();
y = (Integer) save.readObject();
z = (Integer) save.readObject();
name = (String) save.readObject();
setting = (String) save.readObject();
plant = (String) save.readObject();
stuff = (ArrayList) save.readObject();

// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace(); // If there was an error, print the info.
}

// Print the values, to see that they've been recovered.
System.out.println("\nRestored Object Values:\n");
System.out.println("\tpowerSwitch: " + powerSwitch);
System.out.println("\tx=" + x + " y=" + y + " z=" + z);
System.out.println("\tname: " + name);
System.out.println("\tsetting: " + setting);
System.out.println("\tplant: " + plant);
System.out.println("\tContents of stuff: ");
System.out.println("\t\t" + stuff);
System.out.println();

// All done.
}
}

<<Return to How to Save to a File with Java

The example programs can be downloaded at:
Begin With Java Code Downloads
StumbleUpon