Created
February 22, 2013 20:44
-
-
Save tonetheman/5016416 to your computer and use it in GitHub Desktop.
cow serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package moo; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
public class CowTester { | |
static class Cow implements Serializable { | |
int cowid=-1; | |
public Cow(int cowid) { | |
this.cowid = cowid; | |
} | |
public String toString() { | |
return "moo: " + Integer.toString(this.cowid); | |
} | |
} | |
public static int COWCOUNT = 2; | |
public static String FILENAME = "c:\\tmp\\cows.ser"; | |
public static void deletecows() throws Exception { | |
File file = new File(FILENAME); | |
if (!file.delete()) { | |
System.out.println("ERR: unable to delete cows"); | |
} | |
} | |
public static void writecows() throws Exception { | |
Cow[] cows = new Cow[COWCOUNT]; | |
cows[0] = new Cow(100); | |
cows[1] = new Cow(200); | |
FileOutputStream fout = new FileOutputStream(FILENAME); | |
ObjectOutputStream out = new ObjectOutputStream(fout); | |
out.writeInt(COWCOUNT); | |
for(int i=0;i<cows.length;i++) { | |
out.writeObject(cows[i]); | |
} | |
out.close(); | |
fout.close(); | |
} | |
public static void readcows() throws Exception { | |
Cow[] cows = new Cow[COWCOUNT]; | |
FileInputStream finf = new FileInputStream(FILENAME); | |
ObjectInputStream in = new ObjectInputStream(finf); | |
int cow_count = in.readInt(); | |
for(int i=0;i<cow_count;i++) { | |
cows[i] = (Cow)in.readObject(); | |
} | |
in.close(); | |
finf.close(); | |
printcows(cows); | |
} | |
public static void printcows(Cow[] cows) { | |
for(int i=0;i<cows.length;i++) { | |
System.out.println(cows[i]); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
deletecows(); | |
writecows(); | |
readcows(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment