Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Object serialization and try/catch

$
0
0
I am having some trouble understanding the order of execution in the try/catch statement. Staying close to the code in my textbook (for purposes of understanding their code), I have the following in my WriteData.java file:
import java.io.*;
import java.util.Scanner;

public class WriteData 
{
	private static int number;
	private static String name; 
	private static float money;
	private static ObjectOutputStream output;	//This is for the output. Make sure that
	//this object gets an instance of FileOutputStream so that it can write objects
	//to a FILE.
	static Scanner input = new Scanner(System.in);
	static DataClass d;
	
	public static void openfile()
	{
		//Try opening a file (it must have the ".ser" extension).
		try
		{
			output = new ObjectOutputStream(new FileOutputStream("test.ser"));
		}
		//If there is a failure, throw the necessary error.
		catch (IOException exception)
		{
			System.out.println("Error opening file.");
		}
	}
	public static void writedata()
	{
		//write the data until the user enters a sentry value.
		System.out.println("Enter CTRL + z to stop input.\n");
		while (input.hasNext())
		{
			System.out.print ("Enter the data in the following format: " +
						"account_number name balance\n->");
			try
			{
				number = input.nextInt();
				name = input.next();
				money = input.nextFloat();
				
				//Make object with that data
				d = new DataClass(number, name, money);
				//write it to the file
				output.writeObject(d);
			}
			catch (IOException e)
			{
				System.out.println("Error writing to file.");
				return;
			}
		}
		System.out.println("\n");
	}	//end writedata
	public static void closefile()
	{
		try 
		{
			if (output != null)
			{
				output.close();
			}
		}
		catch (IOException e)
		{
			System.out.println("Error closing file. Take precautions");
			System.exit(1);
		}
	}
}


When this executes, it wants to, for some reason, wait for my input and then prompt me for it! There has to be something wrong here! For some reason, the textbook put the prompt at the end of the while statement (and after all the try-catch statements), and I don't understand the flow of such statements. Also, in the ReadData.java file, I went closer to what they were trying to do. I don't feel comfortable with using the following infinite loop:
while (true)
{
//read in objects
}
catch (EOFException eof)
{
	return;
} 


I think this is because I have done most of my programming in C++, where there exist features like:
while (myfile.good())
{
        //some stuff
}


Is this natural? (My game MIGHT have to read in all the data from the .ser file; it will be storing encrypted data to the file for the purpose of conducting a beta-test.)

Viewing all articles
Browse latest Browse all 51036

Trending Articles