Java Problems With Deserialization - java

I know that this question has been addressed before,but i simply cannot find the answer no matter how hard i try.
I am trying to serialize and deserialize objects in Java. I am having problems in the deserialization. I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848. Why do i get this instead of the actual values typed in?
Here is my code
package prueba;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prueba {
public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {
File file = new File("f.txt");
List <Estudiantes> lista = new ArrayList<>();
boolean continuar = true;
while (continuar == true){
Estudiantes es = new Estudiantes();
System.out.println("Ingrese nombre");
Scanner kb = new Scanner(System.in);
es.nombre = kb.nextLine();
System.out.println("Ingrese Apellido");
Scanner kb1 = new Scanner(System.in);
es.apellido = kb1.nextLine();
System.out.println("Ingrese Número");
Scanner kb2 = new Scanner(System.in);
es.numero = kb2.nextInt();
lista.add(es);
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
for (Estudiantes est: lista){
output.writeObject(est);
}
output.close();
fo.close();
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
ArrayList<Estudiantes> est2 = new ArrayList<Estudiantes>();
try {
while (true){
Estudiantes s = (Estudiantes)input.readObject();
est2.add(s);
}
}
catch (EOFException ex){}
for (Estudiantes s :est2){
System.out.println(s);
fi.close();
input.close();
}
System.out.println("0 para salir; 1 para continuar");
Scanner kb3 = new Scanner(System.in);
int rev = kb3.nextInt();
if (rev == 0){
continuar = false;
System.out.println("Hasta Luego");
}
}
}
}
And here is my Estudiantes class
package prueba;
import java.io.Serializable;
public class Estudiantes implements Serializable{
String nombre, apellido;
int numero;
}
Thanks

I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848
That's what you get when you explicitly or implicitly call toString() on an object whose class hasn't overridden it.
It isn't evidence that you have a problem.

I think if you are getting the values like prueba.Estudiantes#1bd7848 you are its already been deserialized. You just have to override the toString() properly to get the output. Not sure if this helps

When you try to print your class when reading back the objects you previously wrote you have to implement the toString() method from the Object class here is what I mean.
Change your class to this:
public class Estudiantes implements Serializable {
private static final long serialVersionUID = 123L; // has to be unique
String nombre, apellido;
int numero;
#Override
public String toString() {
System.out.println("first name: " + nombre);
System.out.println("last name: " + apellido);
System.out.println(numero);
return // a string you want to print
}
}

Related

Junit: how to stimulate the scanner.nextFloat() in testing?

I am writing Service for adding new Menu Items to Menu. Everything works fine with the tutorial which guided how to stimulate the System.in in Junit test.
However, one parameter of Menu Items need to set to float value is Menu Item price. As a result, the String input I provided by ByteArrayInputStream and System.setIn doesn't seem to change the String values to Float value as I expected.
This is my service code:
public class DailyMenuServicesImpl implements DailyMenuServices {
private MenuPrinter menuPrinter;
public DailyMenuServicesImpl(){
this.menuPrinter = new MenuPrinterImpl();
}
#Override
public DailyMenu addMenuItemsToMenu(DailyMenu dailyMenu) {
Scanner scanner = new Scanner(System.in);
MenuItem menuItem = new MenuItem();
List<MenuItem> menuItemList = dailyMenu.getMenuItemList();
try {
System.out.print("\nInsert menu item name: ");
menuItem.setNames(scanner.nextLine());
System.out.print("Insert menu item description: ");
menuItem.setDescription(scanner.nextLine());
System.out.print("Insert menu item image: ");
menuItem.setImage(scanner.nextLine());
System.out.print("Insert menu item price:");
menuItem.setPrice(scanner.nextFloat()); // this is the problem everything above works fine.
menuItemList.add(menuItem);
dailyMenu.setMenuItemList(menuItemList);
}catch (IllegalStateException exception){
System.out.println(exception.getMessage());
}catch (InputMismatchException exception){
System.out.println(new InputMismatchException("Menu item price must be number !!!").getMessage());
}
return dailyMenu;
}
}
And here is my unit test:
#RunWith(MockitoJUnitRunner.class)
public class DailyMenuServiceTest {
private MenuPrinter menuPrinter;
private DailyMenuServices dailyMenuServices;
private final InputStream systemIn = System.in;
private final PrintStream systemOut = System.out;
private ByteArrayInputStream testIn;
private ByteArrayOutputStream testOut;
#Before
public void init(){
dailyMenuServices = new DailyMenuServicesImpl();
testOut = new ByteArrayOutputStream();
menuPrinter = new MenuPrinterImpl();
System.setOut(new PrintStream(testOut));
}
#After
public void restoreSystemInputOutput(){
System.setIn(systemIn);
System.setOut(systemOut);
}
#Test
public void whenAddNewMenuItemsToMenu_returnNewDailyMenu(){
List<MenuItem> menuItemList = new ArrayList<>();
DailyMenu dailyMenu = new DailyMenu(menuItemList);
provideInput("Pizza\nGood\nItaly\n4.56f");
dailyMenu = dailyMenuServices.addMenuItemsToMenu(dailyMenu);
menuPrinter.printMenu(dailyMenu);
String expected = "Names: Pizza - Price: 4.56$";
assertEquals(expected,testOut.toString());
}
private void provideInput(String data){
testIn = new ByteArrayInputStream(data.getBytes());
System.setIn(testIn);
}
So how I can set the Menu Item price parameter as Float values if I use the ByteArrayInputStream like tutorial? All your supports are big helps to me.
You can use the System Rules to pass in the user input from the Java.lang.System I believe.You can find more information here: https://stefanbirkner.github.io/system-rules
Keep in mind this is an external Library
Syntax Should be
import java.util.Scanner;
public class Summarize {
public static int sumOfNumbersFromSystemIn() {
Scanner scanner = new Scanner(System.in);
int firstSummand = scanner.nextInt();
int secondSummand = scanner.nextInt();
return firstSummand + secondSummand;
}
}
import static org.junit.Assert.*;
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
public class SummarizeTest {
#Rule
public final TextFromStandardInputStream systemInMock
= emptyStandardInputStream();
#Test
public void summarizesTwoNumbers() {
systemInMock.provideLines("1", "2");
assertEquals(3, Summarize.sumOfNumbersFromSystemIn());
}
}

can not open the file in java program

I need to open file but it give me an error in the main function
I'm trying to let the user but the file name if it is not correct the program will give an error message and terminate the program
Here is my program.
//import java.io.File;
//import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*; // file input/output
import java.io.IOException;
public class Stock{
String name;
String symbol;
double Price;
//Random randomNumbers = new Random();//Generate random numbers
Stock(){ // no-argument constructor
name="";
symbol="";
Price=0.0;
}
Stock(String n,String s,double p){ //constructor with argument
name=n;
symbol=s;
Price=p;
}
public void setname(String name){//mutators to set the value of name
this.name=name;
}
public void setsymbol(String symbol){//mutators to set the value of symbol
this.symbol=symbol;
}
public void setnextPrice(double price){
this.Price = price;
}
public String getname(){//accessor to get the name
return name;
}
public String getsymbol(){ //accessor to get the symbol
return symbol;
}
public double getPrice(){//accessor to get currentPrice
return Price;
}
public void openfile()throws IOException{
String f="";
System.out.print("Please enter the file name: "+f);
if (f.equals("stocks.txt")){
Scanner x;
x= new Scanner(new File("stocks.txt"));
//PrintWriter outputFile = new PrintWriter("output.txt");
String name = x.nextLine();
System.out.println(name);
}
else{
System.out.println("File Not Found");
return;
}
}
}
I assume you are trying to read a file named stocks.txt and get it's contents line by line, you can do this in multiple ways
using Files API
import java.nio.file.Files;
import java.nio.file.Paths;
List lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
iterate over this list and get content
using Scanner
File file = new File("stock.txt");
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
Using
File file = new File("stocks.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
}
catch (..) {}
you can use either one of way to achieve it, using Files API is easier way.

Create and populate HashMap<Integer, ArrayList<object>>

I have an assignment for school that's all about using files, HashMap and ArrayList. This assignment requires 4 classes.
The first class is called FileReader and reads a txt file which is written line by line and each field that we need is separated by ";", for example ("Columbia University";"USA";78.86;2012). Each line contains 2 strings (university name and country) and 2 numbers (score and year). The FileReader class after reading the txt file returns its content in an arraylist.
The second class of the assignment is called UniversityScores and it has 4 fields (uniname, country, score, year), a constructor, accessor methods for all fields and a toString method.
The third class is the heart of our program. This class is called FileEditor and creates a Hashmap<Integer,ArrayList<UniversityScores>> where the key is the year field of each object and value I guess is the rest of the line. My problem is filling the right way the HashMap.
Also, my final 4th class is called FileWriter which creates a new txt and writes inside of it. All my classes work as supposed to except my FileEditor class. Any help needed. Thank you in advance!
Edit
I am supposed to write some other methods as well. For now my problem is the FileEditor class. I also posted the TestFiles class which contains the main function.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class FileReader{
private String fileName;
private Scanner scanner;
private File file;
private ArrayList<String> arrayList;
private String line;
public FileReader(String otherFileName){
this.fileName = otherFileName;
this.file = new File(fileName);
}
public boolean initReader(){
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("Just caught a FileNotFoundException.");
}
if(file.exists()){
return true;
}
else{
return false;
}
}
public ArrayList<String> readFile(){
this.arrayList = new ArrayList<String>();
while (scanner.hasNextLine()) {
this.line = scanner.nextLine();
arrayList.add(line);
}
arrayList.remove(0);
//System.out.println(arrayList);
return arrayList;
}
public void closeReader(){
scanner.close();
System.out.println("Scanner closed");
}
}
‌
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
class FileWriter{
private String path;
private PrintWriter writer;
private File outputFile;
public FileWriter(String otherPath){
this.path = otherPath;
this.outputFile = new File(path);
}
public boolean initWriter(){
try{
writer = new PrintWriter(path);
}
catch (FileNotFoundException e){
System.out.println("just caught an exception");
}
if(outputFile.exists()){
return true;
}
else{
return false;
}
}
public void writeFile(){
writer.println("The first line");
writer.println("The second line");
writer.println("Christos");
}
public void closeWriter(){
writer.close();
System.out.println("Writer closed");
}
}
‌
class UniversityScore{
private String name;
private String country;
private double score;
private int year;
public UniversityScore(String otherName, String otherCountry, double otherScore, int otherYear){
this.name = otherName;
this.country = otherCountry;
this.score = otherScore;
this.year = otherYear;
}
public String getName(){
return name;
}
public String getCountry(){
return country;
}
public double getScore(){
return score;
}
public int getYear(){
return year;
}
public String toString(){
String outputString = name + "\t" + country + "\t" + score + "\t" + year;
return outputString;
}
}
‌
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
class FileEditor{
private HashMap<Integer, ArrayList<UniversityScore>> scores = new HashMap<Integer, ArrayList<UniversityScore>>();
private ArrayList<String> lines;
public FileEditor(ArrayList<String> otherLines){
this.lines = otherLines;
}
public void fillHashMap(){
// that's where I need help
}
}
public class TestFiles {
public static void main(String[] args){
FileReader reader = new FileReader("universities.txt");
if(reader.initReader()){
FileEditor editor = new FileEditor(reader.readFile());
reader.closeReader();
editor.fillHashMap();
FileWriter writer = new FileWriter("universities_2015_output.txt");
if(writer.initWriter()){
writer.writeFile(editor.getScoresOfYear(2015));
writer.closeWriter();
}
else{
System.out.println("Error creating file");
}
System.out.println("Average university score of year 2015: "+editor.getAverageOfYear(2015));
System.out.println("Min university score of year 2015: "+editor.getMinOfYear(2015));
System.out.println("Max university score of year 2015: "+editor.getMaxOfYear(2015));
}
else{
System.out.println("Error opening file");
}
}
}
You will need a way to parse your lines into UniversityScore objects.
Now that you have all the scores, you can add it to your map, according to their year values (may be score but the type doesn't match nor makes practical sense), for example:
for(String line : lines){
String[] vals = line.split(";");
UniversityScore score = new UniversityScore(vals[0],vals[1],Double.parseDouble(vals[2]),Integer.parseInt(vals[3]))
if(scores.containsKey(score.getYear()){ // If the key exists
scores.get(score.getYear()).add(score);
}else{ // If the key doesn't exist, it must be created and added to the map
ArrayList<UniversityScore> newList = new ArrayList<>();
newList.add(score);
scores.put(score.getYear(), newList)
}
}
I noticed your map has an Integer key which corresponds to the year property of a score, so I assumed the map's keys are the years and not the scores as you suggested.
I didn't check if the code works, but it should at least give you an idea on how to fill your map.
It looks like you're being tasked with reading data from a file, and then generating some stats about the data in the file.
Currently, you're simply plopping each line in the ArrayList.
Looks like your next step is to go through each item in that list, and create a UniversityScore object. This is where you will have to parse each string into values that can be assigned to the various fields in the UniversityScore object. When you have done that, put the current line number (as an Integer key) and UniversityScore (as the value) in your HashMap.
Once you have done that, you will have to write the missing methods getScoresOfYear(Integer year), getAverageOfYear(int year), getMinOfYear(int year), and getMaxOfYear(int year) in the editor class.
try this:
public void fillHashMap() {
for(String line : lines) {
String [] fields = line.split(";");
UniversityScores us = new UniversityScores(fields[0], fields[1], fields[2], fields[3]);
if (scores.keySet().contains(us.getScore())) {
scores.get(us.getScore()).add(us);
}
else {
ArrayList<UniversityScores> t = new ArrayList<UniversityScores>();
t.add(us);
scores.put(us.getScore(), t);
}
}
}

Why am I getting a ClassCastException when deserializing an object that contains a treemap?

I'm getting a ClassCastException when I deserialize my object from a file. When I check the file the object is there, so I know it's being serialized correctly. For some reason the code breaks when trying to retrieve the object. The idea is to allow the user to check, by date, all the workouts they've recorded in their log. Also, I've tried implementing a comparator, but I kept getting the same error and I'm all out of ideas. Any help would be much appreciated.
Here is the code that is causing the trouble:
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
}
Here is the workoutLog class:
public class WorkoutLog implements Serializable{
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
I'm including the body of the code for context
package com.alejandro;
import com.alejandro.Utilities.SerializationUtil;
import com.alejandro.model.Exercise;
import com.alejandro.model.Workout;
import com.alejandro.model.WorkoutLog;
import com.sun.istack.internal.NotNull;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;
public class Logger {
public static final String COMPLETE_KEY = "COMPLETE";
public static final String INCOMPLETE_KEY = "INCOMPLETE";
public static final String ADD_KEY = "ADD";
public static final String CHECK_KEY = "CHECK";
public static final String EXIT_KEY = "EXIT";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Logger logger = new Logger();
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
File file = new File("workout.txt");
//im going to need to ask if the user wants to add a workout, close the program, or select a workout
String userInput = checkUserIntention();
//the switch statement goes through all the possible user inputs
switch(userInput){
case Logger.ADD_KEY:
printInstructions();
do{
logger.promptForExerciseData(workout);
}while(!checkIfUserIsDone());
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
break;
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(ClassCastException E){
E.printStackTrace();
}
break;
case Logger.EXIT_KEY:
System.out.println("\nExiting program...");
break;
}
}
//I'm using this method to explain to the user how to use the program
protected static void printInstructions(){
System.out.println("\nWelcome to Mr.Strong!\n");
System.out.println("This program was developed to help powerlifters keep a log of their lifts.\n");
System.out.println("Because of this, the program will only recognize the following lifts:\n");
System.out.println("Squat, Bench, Deadlift, Press.\n");
System.out.println("The program is case-sensitive, make sure the information is entered as stated above.\n");
}
//this method asks the user for information about the lifts stores them in a workout object
//the methods used here are all organized throught the page, its just to keep things cleaner and separate
protected void promptForExerciseData(Workout workout){
Exercise exercise = new Exercise();
askForExerciseIdentity(exercise);
askForNumsRelLifts(exercise);
workout.getExerciseList().add(exercise);
}
//this will check to see if the user is done inputting the exercises he did, if he finished the program ends.
protected static boolean checkIfUserIsDone(){
Scanner scanner = new Scanner(System.in);
boolean isUserDone = false;
System.out.println("\nEnter: 'complete'" + ", if you are done. " +
"If not, enter:'incomplete " + ".\n");
String answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.COMPLETE_KEY)){
isUserDone = true;
} else if(answer.trim().toUpperCase().equals(Logger.INCOMPLETE_KEY)){
isUserDone = false;
} else{
checkIfUserIsDone();
}
return isUserDone;
}
//check if user wants to add, review, or close
protected static String checkUserIntention(){
String answer = "a";
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease choose an option:\n" +
"1-) Add a workout. Enter 'Add'.\n" +
"2-) Check a workout Enter 'Check'.\n" +
"3-) Exit the program. Enter 'Exit'\n");
answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.ADD_KEY) ||
answer.trim().toUpperCase().equals(Logger.CHECK_KEY)||
answer.trim().toUpperCase().equals(Logger.EXIT_KEY)){
return answer.toUpperCase();
}else{
System.out.println("Incorrect input.");
checkUserIntention();
}
return answer;
}
//all of this part is asking for the exercise data
//this is the part that asks for exercise id
protected void askForExerciseIdentity(Exercise exercise){
Scanner scanner = new Scanner(System.in);
do{
System.out.println("\nEnter a lift:\n");
String exerciseIdentity = scanner.nextLine();
if(exerciseIdentity.equals(exercise.SQUAT_KEY)){
exercise.setExerciseIdentity(exercise.SQUAT_KEY);
}else if(exerciseIdentity.equals(exercise.PRESS_KEY)){
exercise.setExerciseIdentity(exercise.PRESS_KEY);
}else if(exerciseIdentity.equals(exercise.BENCH_KEY)){
exercise.setExerciseIdentity(exercise.BENCH_KEY);
}else if(exerciseIdentity.equals(exercise.DEADLIFT_KEY)){
exercise.setExerciseIdentity(exercise.DEADLIFT_KEY);
}else {
exercise.setExerciseIdentity(null);
System.out.println("Please enter a valid exercise.");
}}while(exercise.getExerciseIdentity() == null);
}
//this is the part that aks for numbers
protected void askForNumsRelLifts(Exercise exercise){
exercise.setWeightUsed(askForWeightUsed());
exercise.setNumOfReps(askForNumOfReps());
exercise.setNumOfSets(askForNumOfSets());
}
protected double askForWeightUsed(){
Scanner scanner = new Scanner(System.in);
double weightUsed;
do{
try{
System.out.println("\nEnter weight used:\n");
weightUsed = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
weightUsed = 0;
}
} while(weightUsed == 0);
return weightUsed;
}
protected double askForNumOfSets(){
Scanner scanner = new Scanner(System.in);
double numOfSets;
do{
try{
System.out.println("\nEnter sets done:\n");
numOfSets = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
numOfSets = 0;
}
}while(numOfSets == 0);
return numOfSets;
}
protected double askForNumOfReps(){
Scanner scanner = new Scanner(System.in);
double reps;
do{
try{
System.out.println("\nEnter reps done:\n");
reps = Double.parseDouble(scanner.nextLine());
} catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
reps = 0;
}
}while(reps == 0);
return reps;
}
}
Here is workout included:
public class Workout implements Serializable{
protected ArrayList<Exercise> mExerciseList;
protected Date mDateCreated;
public Workout(){
mExerciseList = new ArrayList<>();
mDateCreated = new Date();
}
public ArrayList<Exercise> getExerciseList(){
return mExerciseList;
}
public String getDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(mDateCreated);
}}
Here is the seralizationutil:
import com.alejandro.model.WorkoutLog;
import java.io.*;
public class SerializationUtil{
public static Object deserialize(File filename) throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(filename);
Object obj = new Object();
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
while(fis.available()>0){
obj = ois.readObject();
}
ois.close();
return obj;
}
public static void serialize(Object object, File filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.close();
}}
Here is what the compiler gives me:
java.lang.ClassCastException: java.lang.Object cannot be cast to com.alejandro.model.WorkoutLog
at com.alejandro.Logger.main(Logger.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
just try this simple example, i have modified your code extensively
one more thing, I dont know what implementation you have under SerializationUtil so i created my own implementation
My example works without any issue
package week4;
import java.io.Serializable;
import java.util.TreeMap;
public class WorkoutLog implements Serializable {
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
}
package week4;
import java.io.Serializable;
public class Workout implements Serializable {
String date = "2016-01-13";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
package week4;
import java.io.File;
import java.io.IOException;
public class TestWorkOut {
public static void main(String[] args) throws IOException, ClassNotFoundException {
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
/* I had path to workout.txt as D:\\workout.txt*/
File file = new File("D:\\workout.txt");
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
}
}
package week4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
public static void serialize(WorkoutLog workoutLog, File filename) {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(workoutLog);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static WorkoutLog deserialize(File filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
WorkoutLog workout = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
workout = (WorkoutLog) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return workout;
}
}
Output
Workout saved in...workout.txt
Deserializing from:...workout.txt
[2016-01-13]

File Handling and Arraylists error

I'm trying to add a list of phrases from the text file "ListOfElectronics.txt", to the ArrayList "electronics".
I'm getting an error here: electronics.add(fileIn.nextLine());
It's saying "no suitable method found for add(java.lang.String)"
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
/***
*
*
*
*/
public class Driver
{
public static void main(String[] args)
{
System.out.println("\f");
ArrayList<Electronics> electronics = new ArrayList<Electronics>();
Scanner stdIn = new Scanner(System.in);
Scanner fileIn;
try
{
fileIn = new Scanner(new FileReader("ListOfElectronics.txt"));
while (fileIn.hasNextLine())
{
electronics.add(fileIn.nextLine());
}
fileIn.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
Replace
ArrayList<Electronics> electronics = new ArrayList<Electronics>();
with
ArrayList<String> electronics = new ArrayList<>();
Otherwise, it's expecting you to add objects of a class of a type called Electronics.
If you do have a class called Electronics, that you're looking to add to the Arraylist, and if it has a constructor that calls for a String, you can replace the add string with:
electronics.add(new Electronics(fileIn.nextLine()));
If your Electronics class looks like this
public class Electronics {
private string name;
public Electronics(String name) {
this.name = name;
}
}
then you could just replace:
while (fileIn.hasNextLine())
{
electronics.add(fileIn.nextLine());
}
with
while (fileIn.hasNextLine())
{
Electronics electronics = new Electronics(fileIn.nextLine();
electronics.add(electronics);
}

Categories