Operating on a file in java - java

I'm having a bit of a problem with all the FileReaders and FileWriters in java. I want my program to get the name of the person and then after asking them a couple of questions evaluate their score. That is pretty easy but now what I want to do is to document it in a log file like this:
Jacob : 10
Mark : 15
Steve : 7
And then every time any of these people open the program it will retrieve their current score or if it is someone new it would append their name and score.
I can't find a way to search a file and then retrieve the integer at the end.
EDIT:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Main {
static Scores scoreClass = new Scores();
private static void setupMap() {
try {
FileInputStream fin = new FileInputStream("scores.map");
#SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fin);
scoreClass = (Scores) ois.readObject();
} catch (Exception e) {
System.err.println("Could not load score data");
e.printStackTrace();
}
}
private static void saveMap() {
try {
FileOutputStream fout = new FileOutputStream("scores.map");
#SuppressWarnings("resource")
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(scoreClass);
} catch (Exception e) {
System.err.println("Could not save score data");
e.printStackTrace();
}
}
public static void main(String[] args) {
setupMap();
int score = 0;
String guess;
String[][] questions_with_answers = {{"I __________ to school.(go)", "She __________ tennis. (play)", "She _______ a bitch. (be)"}, {"am going", "was playing", "is being"}};
Scanner answer = new Scanner(System.in);
Scanner studentInput = new Scanner(System.in);
System.out.println("What is your name?");
String name = answer.nextLine();
if(Scores.getScore(name) == -1){
Scores.setScore(name, score);
} else {
Scores.getScore(name);
}
System.out.println("Hello " + name + ". Your score is: " + score);
for(int i = 0; i < (questions_with_answers[0].length); i++){
System.out.println(questions_with_answers[0][i]);
guess = studentInput.nextLine();
if(guess.equals(questions_with_answers[1][i])){
System.out.println("Correct! You get 1 point.");
score = score + 1;
System.out.println("Your score is " + score);
} else {
System.out.println("You made a mistake! No points...");
}
}
System.out.printf("Congrats! You finished the test with "+ score +" points out of " + questions_with_answers[0].length);
Scores.setScore(name, score);
saveMap();
answer.close();
studentInput.close();
}
}
This doesn't throw any exceptions but still doesn't read the input from the file :/

You could store the data as a hash map and then serialize it to a save file
I wrote an example that includes a class called Scores which has methods to read a score and add a score to a contained hash map. I also added methods in the main class for saving and opening a file that will contain the score class data.
Main Class:
public class Main {
static Scores scoreClass = new Scores();
public static void main(String[] args) {
setupMap();
//Do score calculations
saveMap();
}
private static void setupMap() {
try {
FileInputStream fin = new FileInputStream("scores.map");
#SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fin);
scoreClass = (Scores) ois.readObject();
} catch (Exception e) {
System.err.println("Could not load score data");
e.printStackTrace();
}
}
private static void saveMap() {
try {
FileOutputStream fout = new FileOutputStream("scores.map");
#SuppressWarnings("resource")
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(scoreClass);
} catch (Exception e) {
System.err.println("Could not save score data");
e.printStackTrace();
}
}
}
Scores Class:
public class Scores implements Serializable{
private static final long serialVersionUID = 1L;
public static Map<String, Integer> scoreMap = new HashMap<String, Integer>();
public static int getScore(String name) {
if (scoreMap.containsKey(name)) {
return scoreMap.get(name);
} else {
return -1;
}
}
public static void setScore(String name, int score) {
scoreMap.put(name, score);
}
}

Related

java howto load and save a ArrayList object

I've pair the code down to the methods I am having a problem, with. It 'seems' to work until I try to load the file again, and it comes up with nothing in it. (I have not fully understood how to clear the ArrayList before performing the 2nd load, but that is for later).
I am sorry if this is hidden somewhere under some other nomenclature I also have not learned yet, but this is a project that is due tomorrow and I am at my wit's end.
import java.util.*;
import java.io.*;
public class MainATM3 {
public static ArrayList<ClientAccount> accounts = new ArrayList<ClientAccount>();
public static ClientAccount editBankAccount = new ClientAccount("placeholder",1234,1);;
public static void main(String[] args) {
// Create ATM account ArrayList
ArrayList<ClientAccount> accounts = new ArrayList<ClientAccount>();
// Get Account data from files
initialLoadATMAccounts(accounts);
System.out.println("Loaded "+accounts.size());
System.out.println("before Array "+(accounts.size()));
accounts.add(0,new ClientAccount("Jess",500,1830));
accounts.add(1,new ClientAccount("Mary",1111.11,7890));
System.out.println("after Array "+(accounts.size()));
saveATMAccounts(accounts);
System.out.println("saved "+(accounts.size()));
initialLoadATMAccounts(accounts);
System.out.println("Loaded "+accounts.size());
System.out.println("Logged Out");
}
// Save ArrayList of ATM Objects //call by: saveATMAccounts(accounts);
public static void saveATMAccounts(ArrayList<ClientAccount> saveAccounts) {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
try{
fout=new FileOutputStream("ATMAccounts.sav");
oos = new ObjectOutputStream(fout);
oos.writeObject(accounts);
System.out.println("objects written "+(accounts.size()));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// INITIAL Load ArrayList of ATM Objects //call by: initialLoadATMAccounts(accounts);
public static void initialLoadATMAccounts(ArrayList<ClientAccount> loadAccounts){
FileInputStream fIS = null;
ObjectInputStream oIS = null;
try{
fIS=new FileInputStream("ATMAccounts.sav");
oIS = new ObjectInputStream(fIS);
ArrayList<ClientAccount> loadAccounts = (ArrayList<ClientAccount>) oIS.readObject();
oIS.close();
fIS.close();
}
catch(Exception exc){
exc.printStackTrace();
}
}
}
import java.io.Serializable;
public class ClientAccount implements Serializable {
public String accountName;
public double accountBalance;
public int accountPIN;
public ClientAccount(String accountName, double accountBalance, int accountPIN){
this.accountName=accountName;
this.accountBalance=accountBalance;
this.accountPIN=accountPIN;
}
// Account Name Methods
public String getAccountName() {
return accountName;
}
public void setAccountName(String name) {
accountName = name;
}
// Account Balance Methods
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double balance) {
accountBalance = balance;
}
// PIN Methods
public int getAccountPIN() {
return accountPIN;
}
public void setAccountPIN(int newPIN) {
accountPIN = newPIN;
}
}
Instead of passing the desired array to initialLoadATMAccounts as param you should return the new, loaded array:
public static List<ClientAccount> initialLoadATMAccounts(){
FileInputStream fIS = null;
ObjectInputStream oIS = null;
try{
fIS=new FileInputStream("ATMAccounts.sav");
oIS = new ObjectInputStream(fIS);
ArrayList<ClientAccount> loadAccounts = (ArrayList<ClientAccount>) oIS.readObject();
oIS.close();
fIS.close();
return loadAccounts;
}
catch(Exception exc){
exc.printStackTrace();
}
}
BTW: A IDE like eclipse would have issued a warning where you overwrite the param loadAccounts.

Adding highscores to java game - From console to JPanel - Saving highscore in encrypted text file

I am new to Java, and learning new things everyday. English is not my mother language, I'm sorry.
So, I'm making a maze game in Java to learn while writing code.
For my maze game, the player needs to get to the exit of the maze asap. And the time he has, needs to be saved in an encrypted text file.
So I've got a package Highscores combining several classes. The code works more or less, it outputs in the console. Now what I need is that that output gets outputted on a JPanel next to my maze. I've added some extra info in the code
Here is my highscore class:
public class Highscore {
// An arraylist of the type "score" we will use to work with the scores inside the class
private ArrayList<Score> scores;
// The name of the file where the highscores will be saved
private static final String highscorefile = "Resources/scores.dat";
//Initialising an in and outputStream for working with the file
ObjectOutputStream output = null;
ObjectInputStream input = null;
public Highscore() {
//initialising the scores-arraylist
scores = new ArrayList<Score>();
}
public ArrayList<Score> getScores() {
loadScoreFile();
sort();
return scores;
}
private void sort() {
ScoreVergelijken comparator = new ScoreVergelijken();
Collections.sort(scores, comparator);
}
public void addScore(String name, int score) {
loadScoreFile();
scores.add(new Score(name, score));
updateScoreFile();
}
public void loadScoreFile() {
try {
input = new ObjectInputStream(new FileInputStream(highscorefile));
scores = (ArrayList<Score>) input.readObject();
} catch (FileNotFoundException e) {
System.out.println("[Laad] FNF Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("[Laad] CNF Error: " + e.getMessage());
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
}
}
}
public void updateScoreFile() {
try {
output = new ObjectOutputStream(new FileOutputStream(highscorefile));
output.writeObject(scores);
} catch (FileNotFoundException e) {
System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and make a new file");
} catch (IOException e) {
System.out.println("[Update] IO Error: " + e.getMessage());
} finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException e) {
System.out.println("[Update] Error: " + e.getMessage());
}
}
}
public String getHighscoreString() {
String highscoreString = "";
int max = 10;
ArrayList<Score> scores;
scores = getScores();
int i = 0;
int x = scores.size();
if (x > max) {
x = max;
}
while (i < x) {
highscoreString += (i + 1) + ".\t" + scores.get(i).getNaam() + "\t\t" + scores.get(i).getScore() + "\n";
i++;
}
return highscoreString;
}
}
Here is my Main class:
public class Main {
public static void main(String[] args) {
Highscore hm = new Highscore();
hm.addScore("Bart",240);
hm.addScore("Marge",300);
hm.addScore("Maggie",220);
hm.addScore("Homer",100);
hm.addScore("Lisa",270);
hm.addScore(LabyrinthProject.View.MainMenu.username,290);
System.out.print(hm.getHighscoreString());
} }
Score class :
public class Score implements Serializable {
private int score;
private String naam;
public Score() {
}
public int getScore() {
return score;
}
public String getNaam() {
return naam;
}
public Score(String naam, int score) {
this.score = score;
this.naam = naam;
}
}
ScoreVergelijken class (which means CompareScore)
public class ScoreVergelijken implements Comparator<Score> {
public int compare(Score score1, Score score2) {
int sc1 = score1.getScore();
int sc2 = score2.getScore();
if (sc1 > sc2){
return -1; // -1 means first score is bigger then second score
}else if (sc1 < sc2){
return +1; // +1 means that score is lower
}else{
return 0; // 0 means score is equal
}
} }
If anyone could explain to me what to use, it would be greatly appreciated! Thank you very much!
Also, how to use those highscores and store them encrypted in a text file. How can I achieve that?
Sincerely, A beginner java student.
to keep your data encrypted in a file, you can use CipherIn/OutputStream, just like this
public static void main(String[] args) throws Exception {
// got this example from http://www.java2s.com/Tutorial/Java/0490__Security/UsingCipherInputStream.htm
write();
read();
}
public static void write() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(new SecureRandom());
SecretKey key = kg.generateKey();
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
oos.writeObject(ks.getKey());
Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
pw.println("Stand and unfold yourself");
pw.flush();
pw.close();
oos.writeObject(c.getIV());
oos.close();
}
public static void read() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keyfile"));
DESKeySpec ks = new DESKeySpec((byte[]) ois.readObject());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey key = skf.generateSecret(ks);
Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));
CipherInputStream cis = new CipherInputStream(new FileInputStream("ciphertext"), c);
BufferedReader br = new BufferedReader(new InputStreamReader(cis));
System.out.println(br.readLine());
}
Basically you asked two questions and Leo answered your second question.
Your first question is...
what I need is that ...[the high scores]... gets outputted on a JPanel next to my maze
You didn't post any GUI code, but a subclass of JTextComponent would be more appropriate than a JPanel. Simply add a component, for example JTextArea and call its setText() method with your high score string as the method argument.

Loading an array of objects using Java Serialization

The following code is two methods, one for saving to a file using object serialization and one for loading and deserializing the saved file for the user to read:
private void SaveDeck() throws Exception {
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
fout = new FileOutputStream(filePath, true);
oos = new ObjectOutputStream(fout);
oos.writeObject(theDeck);
} catch (Exception ex) {
ex.printStackTrace();
}finally {
if(oos != null){
oos.close();
}
}
}
private FlashCardDeck[] loadDeck(){
user.setDeckMade(true);
try {
FileInputStream fis = new FileInputStream(filePath);
ObjectInputStream in = new ObjectInputStream(fis);
this.theDeck = (FlashCardDeck[])in.readObject();
in.close();
}
catch (Exception e) {
System.out.println(e);
}
return theDeck;
}
The error I'm getting is on the load method:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: myPackage.UserInterface
Saving works fine; I've opened up the .ser file after the SaveDeck method has executed and everything seemed to check out properly.
My question is if the problem is with the file itself, the save method, or external methods? I have made sure that everything not serializable (Namely, the Scanner class) is transient.
package myPackage.FlashCards;
import java.io.Serializable;
public class FlashCardDeck implements Serializable{
private static final long serialVersionUID = -1176413113990886560L;
public FlashCard[] theDeck;
public String deckName;
public FlashCardDeck(int cards, String name) {
this.deckName = name;
theDeck = new FlashCard[cards];
for (int i = 0; i < theDeck.length; i++) {
theDeck[i] = new FlashCard(i);
}
}
public String getQuestion(int i) {
return theDeck[i].QuestionToString();
}
public String getAnswer(int i ) {
return theDeck[i].AnswerToString();
}
public String getName() {
return deckName;
}
public int getDeckSize() {
return theDeck.length;
}
}
package myPackage.FlashCards;
import java.io.Serializable;
import java.util.Scanner;
public class FlashCard implements Serializable{
private static final long serialVersionUID = -8880816241107858648L;
private transient Scanner in = new Scanner(System.in);
String question;
String answer;
public FlashCard(int i) {
setCard(i);
}
public void setCard(int cards) {
System.out.println("What is the question for number " + (cards + 1) + "?");
question = in.nextLine();
System.out.println("What is the answer for number " + (cards + 1) + "?");
answer = in.nextLine();
}
public String QuestionToString() {
return "Question: " + question;
}
public String AnswerToString() {
return "Answer: " + answer;
}
}
package myPackage.FlashCards;
import java.io.Serializable;
import java.util.InputMismatchException;
import java.util.Scanner;
public class UserInterface implements Serializable{
private static final long serialVersionUID = 7755668511730129821L;
private int moreThanOnce = 0;
boolean deckMade = false;
private transient Scanner in = new Scanner(System.in);
public int AmountOfDecks() {
int decks;
System.out.println("How many decks will you be creating? (Type the number,
not the word. Ex: 2)");
decks = in.nextInt();
while (decks <= 0) {
System.out.println("You can't have less than one deck! Try again.");
decks = in.nextInt();
}
return decks;
}
public int StartMenu() {
int choice = 0;
moreThanOnce++;
if (moreThanOnce > 1) {
choice = SecondMenu();
} else {
System.out.println("\nFlash Card Creation Engine Ver. 2.5 ALPHA");
System.out.println("Press the cooresponding number for your
choice.");
System.out.println("1. Make a deck of flash cards");
System.out.println("2. Play flash cards");
System.out.println("3. Quit \n");
try { choice = in.nextInt(); } catch (InputMismatchException ime) {}
}
return choice;
}
public int AmountOfCards(int cards) {
int catchMe;
deckMade = true;
System.out.println("How many cards would you like? (Type the number, not the
word. Ex: 2)");
try {
catchMe = in.nextInt();
while (catchMe <= 0) {
System.out.println("You can't have less than one card! Try
again!");
catchMe = in.nextInt();
}
} catch (Exception ime) {
System.out.println("Uh-oh, you did that wrong! Let's try that again.
Try typing: 3");
cards = 0;
catchMe = in.nextInt();
}
cards = catchMe;
return cards;
}
public boolean getDeckMade() {
return deckMade;
}
public void setDeckMade(boolean makeDeckMade) {
this.deckMade = makeDeckMade;
}
public String NameOfDeck() {
String name;
System.out.println("What would you like to name this deck?");
name = in.next();
return name;
}
private int SecondMenu() {
int choice = 0;
System.out.println("Now what would you like to do?");
if (deckMade) {
System.out.println("1. Make or load a deck of flash cards -- DONE");
} else {
System.out.println("1. Make a deck of flash cards.");
}
System.out.println("2. Play flash cards");
System.out.println("3. Quit \n");
try { choice = in.nextInt(); } catch (InputMismatchException ime) {}
return choice;
}
public boolean SetMode() {
boolean timed = false;
int userChoice = 0;
while (userChoice < 1 || userChoice > 2) {
System.out.println("What mode are you selecting?");
System.out.println("1. Timed");
System.out.println("2. Normal");
System.out.println("3. Help");
System.out.println("4. Quit");
userChoice = in.nextInt();
if (userChoice == 1) {
timed = true;
} else if (userChoice == 3) {
System.out.println("Timed: Answers to a flash card will
appear after a set amount of seconds, then show the next
question after the same amount of seconds, which are set by
the user (that's you!)");
System.out.println("Normal: Answers to a flash card will
appear when the user (also you!) presses enter, and wait for
enter to be pressed before showing the next question.");
} else if (userChoice == 4) {
System.out.println("Have a good day.");
System.exit(0);
} else {
System.out.println("Choose from the proivded list -- 1 for
Timed mode, 2 for Normal mode, 3 to show the Help menu, 4 to
quit.");
System.out.println();
}
}
return timed;
}
public String setQuestion(int cards) {
String question = "";
return question;
}
public String setAnswer(int cards) {
String answer = "";
return answer;
}
}
The class you're trying to serialize (and any non-transient objects referenced by that class) must implement the Serializable interface.
judging by the error you have a UserInterface class referenced there which is not serializable.
Edit:
Also
new FileOutputStream(filePath, true);
always appends to the end of the file instead of clearing the file. You may have older data in the file that is not deserialized correctly. You could try removing the file and trying again.
In general - appending different objects to a file may be a bad choice considering data corruption. If different files for each deck are not an option, I might go for a separate DeckStore object that holds all the decks and gets serialized as a whole.
Class that you want to serialize should implement Serializable interface
public class FlashCardDeck implements Serializable {
// Fields and methods of the class ...
}
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

Write and Read a Vector to a serialized file in Java?

I am trying a vector to a serialized file. The vector is made of a class I created. Below is the class.
public class Product implements java.io.Serializable{
public String description;
public String code;
public double price;
public String unit;
public Product(String w, String x, double y, String z){ //Constructor for Product
description = w;
code = x;
price = y;
unit = z;
}
}
I created a vector:
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.ser"));
Vector <Product> products=new Vector();//declare a vector of products
for(int i=0;i<101;i++){//enter the values for the class
System.out.print("Description: ");
String w = in.readLine();
char f = w.charAt(0);
if(f=='#'){//Statement to break out of the loop when the user enters #
System.out.println();
break;
}else{//Code to read input from user
System.out.print("Code: ");
String x = in.readLine().toUpperCase();
boolean finished=false;
while(!finished){
System.out.print("Price: ");
String a =in.readLine();
try{//try catch statement
double y= Double.parseDouble(a);
System.out.print("Unit: ");
String z = in.readLine();
Product temp = new Product(w, x, y, z);
products.insertElementAt(temp, i);//values are assigned to
//the vector elements
System.out.println();
finished=true;
}
catch(Exception e){
System.out.println("do not enter letters for the price");
}
}
}
}
So I have a vector of Product. What I need to know is how to write it to into a serialized file, file.ser, then how to read from that file back into a vector of Product. I have been experimenting with this for a whole day and can't seem to get anything right or find anything useful on the internet.
I added a toString() method do class Product to get proper debug output:
public class Product implements Serializable {
// ....
#Override
public String toString() {
return description + "/" + code + "/" + price + "/" + unit;
}
}
You can put the whole vector instance to the ObjectOutputStream.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
public class Main {
private static final String FILE_NAME = "file.ser";
public static void main(String[] args) throws Exception {
final Vector<Product> products = new Vector<Product>();
products.add(new Product("1", "1", 1.0, "1"));
products.add(new Product("2", "2", 2.0, "2"));
products.add(new Product("3", "3", 3.0, "3"));
products.add(new Product("4", "4", 4.0, "4"));
System.out.println("Original products : " + products);
final ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
try {
out.writeObject(products);
} finally {
out.close();
}
final ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(FILE_NAME)));
final Vector<Product> productsFromFile = (Vector<Product>) in.readObject();
System.out.println("Products from file: " + productsFromFile);
}
}
And the output is:
Original products : [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Products from file: [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Try something like the following to write a serialisable object:
Product product = new Product("Apples", "APP", 1.99, 200);
try{
OutputStream file = new FileOutputStream( "output.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(product);
}
finally{
output.close();
}
}
catch(IOException ex){
System.out.println("Output failed.");
}
To read it in you read do the opposite, putting result into an object as follows:
Product product = (Product)input.readObject();
where input is an ObjectInputStream.
I think that you can use this example to write and read the file:
http://www.java-samples.com/showtutorial.php?tutorialid=392
you can search in google for: "java file reader example"
regards
I think that you forgot to add the vector to the class. In your code you assign temp to new Product, then you add the values to the vector. Vector is filled with new values, but Vector is not part of the class Product. Therefore, the data is still in Vector, but it's will never be saved via serializable. (if this is what you try to accomplish)
Here is a small example (written in Java Processing):
import java.io.*;
GameChar Elf, Troll;
void setup() {
Elf = new GameChar(50, new String[] {
"bow", "sword", "dust"
}
);
Troll = new GameChar(200, new String[] {
"bare hands", "big axe"
}
);
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(sketchPath+"/data/game.txt"));
os.writeObject(Elf);
os.writeObject(Troll);
os.close();
}
catch (Exception e) {
println(e);
}
Elf = null;
Troll = null;
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(sketchPath+"/data/game.txt"));
Elf = (GameChar) is.readObject();
Troll = (GameChar) is.readObject();
println("Elf has "+ Elf.getHealth()+" health, and fights with "+ Elf.getWeapons());
println("Troll has "+ Troll.getHealth()+" health, and fights with "+ Troll.getWeapons());
}
catch (Exception e) {
println(e);
}
}
void draw() {
}
static class GameChar implements Serializable {
int health;
String[] weapons;
GameChar(int h, String[] w) {
health = h;
weapons = w;
}
int getHealth() {
return health;
}
String getWeapons() {
String weaponList = "";
for (String weapon : weapons)
weaponList += weapon + " ";
return weaponList;
}
}

How to Serialize an ArrayLIst in java without getting errors?

I am just trying to output a previously created ArrayList to serialise it for future storage.
but when I attmept to do so I get the runTime error "notSerialisableException: Department.
Is their a speicial way of serializing an arrayList??
Would someone be able to tell me why I may be getting this error.
This is the code:
import java.awt.*;
import java.util.*;
import java.io.*;
import java.io.Serializable;
public class tester1ArrayListObjectSave
{
private ArrayList <Department> allDeps = new ArrayList<Department>();
private int choice = 0;
private String name;
private String loc;
Department theDepartment;
Scanner scan;
public static void main(String[] args)
{
new tester1ArrayListObjectSave();
}
public tester1ArrayListObjectSave()
{
scan = new Scanner(System.in);
options();
}
public void options()
{
System.out.println("wadya wanna do");
System.out.println("1. create a new department");
System.out.println("2. read from text file");
System.out.println("4. save it to system as a serializable file");
System.out.println(". read from text file");
System.out.println("3. to exit");
choice = scan.nextInt();
workOutOptions();
}
public void workOutOptions()
{
if (choice ==1)
{
createNewEmp();
}
else if (choice ==2)
{
try
{
readTextToSystem();
}
catch (IOException exc)
{
System.out.println("uh oh their was an error: "+exc);
}
}
else if (choice == 3)
{
System.exit(0);
}
else if (choice ==4)
{
try
{
createSerialisable();
}
catch (IOException exc)
{
System.out.println("sorry could not serialise data cause of this:"+exc);
}
}
else
{
System.out.println("do nothing");
}
}
public void createNewEmp()
{
System.out.println("What is the name");
name = scan.next();
System.out.println("what is the chaps loc");
loc = scan.next();
try
{
saveToSystem();
}
catch (IOException exc)
{
// do something here to deal with problems
}
theDepartment = new Department(name,loc);
allDeps.add(theDepartment);
options();
}
public void saveToSystem() throws IOException
{
FileOutputStream fos = new FileOutputStream( "backUp.txt", true );
PrintStream outFile = new PrintStream(fos);
System.out.println("added to system succesfully");
outFile.println(name);
outFile.println(loc);
outFile.close();
options();
}
public void readTextToSystem() throws IOException
{
Scanner inFile = new Scanner ( new File ("backUp.txt") );
while (inFile.hasNextLine())
{
name=inFile.nextLine();
System.out.println("this is the name: "+name);
loc = inFile.nextLine();
System.out.println("this is the location: "+loc);
Department dDepartment = new Department(name,loc);
allDeps.add(dDepartment);
options();
}
System.out.println(allDeps);
}
public void createSerialisable() throws IOException
{
FileOutputStream fileOut = new FileOutputStream("theBkup.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allDeps);
options();
}
}
ArrayList isn't the problem; your Department object is.
You need to implement the Serializable interface in that object.

Categories

Resources