I'm stuck trying to deserialize a list of Scores. I spent my entire day searching here but couldn't find a solution.. My code looks something like this:
public class Score implements Comparable<Score>, Serializable {
private String name;
private int score;
// .......
}
public class MySortedList<T> extends...implements...,Serializable {
private ArrayList<T> list;
// ....
}
public class ScoreManager {
private final String FILEPATH;
private final String FILENAME = "highscores.ser";
private MySortedList<Score> scoreList;
public ScoreManager() {
File workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
if ((scoreList = loadScores()) == null) {
scoreList = new MySortedList<Score>();
}
}
public void addScore(Score score) {
scoreList.add(score);
saveScores();
}
public MySortedList<Score> getScoreList() {
return scoreList;
}
private void saveScores() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(scoreList);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MySortedList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MySortedList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The loadScores() method returns just an empty MySortedList everytime.
However program succesfully creates the highscores.ser file in the correct place and I have absolutely no errors. Score objects are added correctly to the MySortedList object.
Any ideas? Perhaps worth mentioning that this is a part of a bigger program made in Swing. the methods in the ScoreManager class is called when the player dies
only if it can help, this code is working for me:
class Score implements Comparable<Score>, Serializable{
private int point;
public Score(int point) {
this.point = point;
}
public int getPoint(){
return point;
}
#Override
public int compareTo(Score o) {
if (o.getPoint() == this.getPoint())
return 0;
return this.point < o.getPoint() ? - 1 : 1;
}
public String toString() {
return "points: " + point;
}
}
class MyList<T> implements Serializable {
private ArrayList<T> list = new ArrayList<>();
public void add(T e){
list.add(e);
}
public void show() {
System.out.println(list);
}
}
public class Main {
File workingFolder;
String FILEPATH;
private final String FILENAME = "highscores.ser";
MyList<Score> list = new MyList<>();
public static void main(String[] args) {
Main main = new Main();
main.createFolder();
main.addItems();
main.saveScores();
MyList<Score> tempList = main.loadScores();
tempList.show();
main.addMoreItems();
main.saveScores();
tempList = main.loadScores();
tempList.show();
}
private void addItems() {
Score sc = new Score(10);
list.add(sc);
}
private void addMoreItems() {
Score sc1 = new Score(20);
list.add(sc1);
Score sc2 = new Score(30);
list.add(sc2);
}
private void createFolder() {
workingFolder = new File("src\\games\\serialized");
if (!workingFolder.exists()) {
workingFolder.mkdir();
}
FILEPATH = workingFolder.getAbsolutePath();
}
private void saveScores() {
System.out.println("before save: " + list);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(FILEPATH, FILENAME)))) {
out.writeObject(list);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private MyList<Score> loadScores() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(FILEPATH, FILENAME)))) {
return (MyList<Score>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Related
I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
I have a file which is storing objects and I have a *getAll() method which needs to return the List<Secretary>. But, I only see single object being printed in console.
I searched for the problem and tried 3 ways but it did not work.
The insert method for inserting object in file is:
#Override
public Secretary insert(Secretary t) {
try {
System.out.println("insert called");
FileOutputStream file = new FileOutputStream
(filename,true);
ObjectOutputStream out = new ObjectOutputStream
(file);
Method for serialization of object
out.writeObject(t);
out.close();
file.close();
return t;
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
I have declared append mode as true as, my file was being replaced by new object when saving.
So,i need to fetch all object from file and need to assign to a list.I tried:
public class SecretaryDaoImpl implements SecretaryDAO{
private String filename = "secretary.txt";
private Secretary sec=null;
#Override
public List<Secretary> getAll() {
//Method 1
try {
Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
List<Secretary> secList=new ArrayList<>();
Method for deserialization of object
secList.add((Secretary)in.readObject());
in.close();
file.close();
System.out.println("Object has been deserialized\n"
+ "Data after Deserialization.");
System.out.println("secList is" +secList);
return secList;
}
catch (IOException ex) {
System.out.println("Secreatary file not found");
return null;
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
return null;
//Method 2
List<Secretary> secList=new ArrayList<>();
ObjectInputStream objectinputstream = null;
try {
FileInputStream streamIn = new FileInputStream(filename);
objectinputstream = new ObjectInputStream(streamIn);
List<Secretary> readCase = (List<Secretary>) objectinputstream.readObject();
for(Secretary s:readCase){
secList.add(s);
}
System.out.println("seclist is" + secList);
return secList;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(objectinputstream != null){
try {
objectinputstream.close();
} catch (IOException ex) {
Logger.getLogger(SecretaryDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Method 3
try{
File file = new File(filename);
List<Secretary> list = new ArrayList<>();
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
list.add((Secretary) ois.readObject());
}
}
System.out.println("getall is"+list);
}
catch(Exception e){
}
return null;
}
}
I have commented out my code but here while posting in stackoverflow I have uncommented all the codes.
My Secretary.java is :
package com.npsc.entity;
import java.io.Serializable;
/**
*
* #author Ashwin
*/
public class Secretary implements Serializable {
private static final long serialVersionUID = 6529685098267757690L;
private int id;
private String userName;
private String password;
private Branch branch;
public String getUserName() {
return userName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Secretary(String userName, String password) {
this.userName = userName;
this.password = password;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
#Override
public String toString() {
return "Secretary{" + "id=" + id + ", userName=" + userName + ", password=" + password + ", branch=" + branch + '}';
}
}
While performing insert operation,my txt file saving objects is:
But,I am unable to read all the object and add in list.Where I am facing the problem?
You will need to store in the file, the number of Secretary objects to read back. You can then determine how many entities to read, and thus repopulate your list.
Something like:
List<Secretary> list;
private void persistList(ObjectOutputStream out) {
out.writeInt(list.size());
for (Secretary sec : list) {
out.writeObject(sec);
}
}
And then to read:
private List<Secretary> readFromStream(ObjectInputStream in) {
int numObjects = in.readInt();
List<Secretary> result = new ArrayList<>(numObjects);
for (int i = 0; i < numObjects; i++) {
result.add((Secretary)in.readObject());
}
return result;
}
This is just a sketch of the technique (and ignores error handling, stream opening/closing etc.); the main thing is to integrate the idea of recording the size of the list, then reading that many Secretaries into your existing code.
Write a List<Secretary> to file and read same back, then you will have all.
write (Secretary s) {
read List<Secretary> currentList ;
currentList.add(s)
write List<Secretary>
}
I am trying to implement a save and load function in my program that saves an arrayList to a textfile and then can later load all of the past lists I have saved and print them out. I am currently using these two methods:
public static void save(Serializable data, String fileName) throws Exception {
try (ObjectOutputStream oos = new ObjectOutputStream((Files.newOutputStream(Paths.get(fileName))))) {
oos.writeObject(data);
}
}
public static Object load(String fileName) throws Exception {
try (ObjectInputStream oos = new ObjectInputStream((Files.newInputStream(Paths.get(fileName))))) {
return oos.readObject();
}
}
As well as a class that represents a list as serializable data.
The problem with this is that it won't save the data after I terminate the program, and when it loads data it prints it with a great deal of extra text besides the list I want it to return. Is there a better or easier way of doing this?
I once had a same problem. So I will show you how to do it ...
Be the below Level class is what is to be saved:
public class Level implements Serializable {
private int level = 1;
private int star;
private int point;
// Constructor
public Level() {
}
public void setLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
public void setStar(int stars) {
this.star = stars;
}
public int getStar() {
return star;
}
public void setPoint(int points) {
this.point = points;
}
public int getPoint() {
return point;
}
#Override
public String toString() {
return "Level-" + level + " " +
(star > 1 ? star + " stars": star + " star") + " " +
(point > 1 ? point + " points" : point + " point") + "\n";
}
}
We will save the list into this file:
private static final String FILENAME = "data.level";
This is the List of our objects:
List<Level> mLevels;
Call this method to save the list into the file:
private void save() {
if(mLevels.isEmpty()) {
return;
}
try
{
ObjectOutputStream oos = new ObjectOutputStream(mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE));
oos.writeObject(mLevels);
}
catch (IOException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Use this method to load the list from saved file. Notice, we cast the list of our object with this (List<Level>) ois.readObject(); in the method:
private void load() {
try
{
ObjectInputStream ois = new ObjectInputStream(mContext.openFileInput(FILENAME));
mLevels = (List<Level>) ois.readObject();
}
catch (IOException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
catch (ClassNotFoundException e)
{
//Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(mLevels == null) {
mLevels = new ArrayList<>();
//Toast.makeText(mContext,"List created",Toast.LENGTH_SHORT).show();
}
}
By now, you should get the idea of how to save your own list.
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.
Recieving the error:
java.io.NotSerializableException
even after implementing Serializable.
I'm simply trying to serialize a Survey object. Here is my code, does anyone have an idea why I am receiving this error?
public void loadData(Survey survey, Test test, Boolean isSurvey) throws FileNotFoundException {
...
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
Survey s = (Survey) ois.readObject();
ois.close();
System.out.println("list size = " + s.questions);
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveData(Survey survey, Test test, Boolean isSurvey, String fileName) {
...
if (isSurvey) {
try {
FileOutputStream fileOut = new FileOutputStream("surveys/" + fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(survey);
out.close();
fileOut.close();
} catch (IOException ex) {
}
} else {
try {
FileOutputStream fileOut = new FileOutputStream("tests/" + fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(test);
out.close();
fileOut.close();
} catch (IOException ex) {
}
}
}
EDIT: Added survey class. My Question class, Main class, and Input class both implement Serializable
package Survey;
import java.io.Serializable;
import java.util.ArrayList;
import IO.Input;
import Question.Question;
public class Survey implements Serializable{
private static final long serialVersionUID = 1L;
protected Main main = new Main();
protected Input input = new Input();
protected String name;
public ArrayList<Question> questions = new ArrayList<Question>();
public void setName() {
...
}
public void displayName() {
...
}
public void displayQuestions() {
...
}
public void mainMenu() {
...
}
public void addQuestionMenu() {
...
}
}