Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: A simple question
|
Posted: Sep 12, 2003 7:48 PM
|
|
Well, you didn't specify the problem very clearly and you didn't explain what things you can understand and what things you can't.
Java file I/O is, for some inexplicable reason, unnecessarily complicated (or maybe there is an explanation; I wonder if Bill has asked any of to Java creators in an interview on Artima about this...). For some reason they didn't make such a common thing simple. Oh well. You can either memorize the various classes you have to use to read and write a file (first learn the necssary APIs, then practice writing a few programs without looking them up), or make yourself a little set of utilities that package and hide all the complexity.
Do you want the output file to be textual? You could use properties if that's the case. If that isn't important, it is pretty easy to just serialize an array of ints, like so:
import java.util.*;
import java.io.*;
class ReadinAndWritin
{
public static void main(String args[]) throws Exception
{
int [] fibs = new int[15];
// Let's fill up the array with some interesting and valuable data:
fibs[0] = 0;
fibs[1] = 1;
for(int i = 2; i < fibs.length; i++ )
fibs[i] = fibs[i-1] + fibs[i-2];
String filename = "c:\\temp\\ReadinAndWritin.serialized";
// Write to file:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(fibs);
out.close();
// Read it in:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
int [] stuff = (int[])in.readObject();
in.close();
// Test that it was read in correctly:
for(int i=0; i < stuff.length; i++)
{
if( stuff[i] != fibs[i] )
System.out.println( "Error at item " + i + ", should be " + fibs[i] + ", but is " + stuff[i] );
else
System.out.println( "Fibonacci of " + i + " was correctly read. It is " + stuff[i] );
}
}
}
|
|