#Override
public Collection<Flight> getAll() {
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)))) {
Object read = ois.readObject();
List<Flight> objects = (ArrayList<Flight>) read;
return objects;
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
return new ArrayList<>();
}
}
#Test
public void testGetAll() {
try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("flights.txt")))) {
Object read = ois.readObject();
expected = (ArrayList<Flight>) read;
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
Collection<Flight> actual = flightService.getAll();
assertEquals(expected, actual);
}
Hi I have serious problem with testing. Is the above code a correct way to test? Please help me
So say your class is given the file to read in the constructor, like this:
class FlightReader {
File file;
public FlightReader(File f) {
file = f;
}
// your getAll here
}
then a test would first create a file of its own with known data, then read it, then verify the results are as expected, like this:
#Test
public void testGetAll() {
Flight f1 = new Flight("ACREG1", "B737");
Flight f2 = new Flight("ACREG2", "A320");
Flight f3 = new Flight("ACREG3", "B777");
List<Flight> written = new ArrayList<>(Arrays.asList(f1, f2, f3));
File tempFile = File.createTempFile("flights", "test");
// write sample data
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(tempFile))) {
oos.writeObject(written);
}
// data is written to a file, read it back using the tested code
FlightReader reader = new FlightReader(tempFile);
List<Flight> readFlights = reader.getAll();
// verify the written and read data are the same
assertThat(readFlights).contains(f1, f2, f3);
}
Some notes:
you should use specific classes - like in this case ArrayList - as little as possible. Why cast to an ArrayList if you just return a Collection in the end?
you shouldn't use Java Serialization at all; it's error-prone, a security risk, and considered a mistake by the Java architects.
Related
I'm implementing serialization, and am trying to make everything as modular as possible. When reading objects from files, I'm trying to use just one function to pass everything to an ArrayList, or something of that sort. Currently I'm doing something like this:
public static ArrayList<Class1> ReadClass1(String fileName) {
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<Class1>();
while (1 != 2) {
p.add((Class1) in.readObject());
}
} catch (Exception e) {
;
}
return p;
}
However, I want to read other classes, let's say Class2 or Class3, and right now I'm copy-pasting the code and just editing everything that says "Class1" to "Class2". Is there a way to pass in a specific type I want to use, like this?
public static ArrayList<myClass> ReadProducts(String fileName, myClass) { //where myClass is a class
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<myClass>();
while (1 != 2) {
p.add((myClass) in.readObject());
}
} catch (Exception e) {
;
}
return p;
}
So that I could reuse the function for different classes?
You can use java Generics. Please find the code below:
public static <T> ArrayList<T> ReadProducts(String fileName, Class<T> t) {
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<T>();
while (1 != 2) {
p.add(t.cast(in.readObject()));
}
} catch (Exception e) {
;
}
return p;
}
I'm trying to serialize an instance from a class using inheritance.
And this is the class where I try to serialize the data
public class Serializacion {
static int agregarProfeTitular(ProfesorTitular p){
int status = 0;
try {
FileOutputStream fos = new FileOutputStream("profestitulares.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
ArrayList pi = conseguirTodosProfesTitulares();
pi.add(p);
oos.writeObject(pi);
oos.close();
fos.close();
status = 1;
} catch (IOException e) {
System.out.println("Error al agregar el prof titular..."+Arrays.toString(e.getStackTrace()));
}
return status;
}
static ArrayList<ProfesorTitular> conseguirTodosProfesTitulares(){
ArrayList<ProfesorTitular> pi = new ArrayList<ProfesorTitular>();
try {
FileInputStream fis = new FileInputStream("profestitulares.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
pi = (ArrayList<ProfesorTitular>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
System.out.println("Error al conseguir a los profes titulares..."+e);
}
return pi;
}
}
At the end the try-catch throws me
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2950)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1534)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:427)
at profesores.Serializacion.conseguirTodosProfesTitulares(Serializacion.java:69)
at profesores.Serializacion.agregarProfeTitular(Serializacion.java:46)
The idea is that when I want to write some data in my file first I get the data that already exists parsing it as an arraylist and then i return that arraylist and i just add the new data. It works writing the file, but reading it doesnt work.
EDIT:
This is the class code that I try to serialize:
public class ProfesorTitular extends Profesor {
int horasBase;
public ProfesorTitular(int id, String nombre, String clase, int horasBase) {
super(id, nombre, clase);
this.horasBase = horasBase;
}
public int getHorasBase() {
return horasBase;
}
public void setHorasBase(int horasBase) {
this.horasBase = horasBase;
}
}
You create a FileOutputStream for the very poorly named file profestitulares.txt. Serialized data is not text and should not be saved in files with the .txt extension.
This creates an empty file.
You then create an ObjectOutputStream around this stream, which writes the object stream header.
You then create a FileInputStream for the same file, which is now empty apart from the object stream header, whatever its state may have previously been.
You then try to create an ObjectInputStream around this, which fails, because there is a stream header but no objects in this logically empty file.
Solution: read the objects from the file before you create the new one.
I need to write a class that has two static methods: writeFile and readFile. However, after I do my readFile(), it returns nothing.
class writereadFile {
public static void writeFile(ArrayList<Object> list, File file){
try {
try (FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(list);
oos.close();
}
}catch(IOException e){e.getMessage();}
}
public static ArrayList<Object> readFile(ArrayList<Object>list, File file){
try {
try (FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis)) {
Object o = ois.readObject();
list = (ArrayList<Object>) o;
ois.close();
}
}catch(IOException | ClassNotFoundException e){e.getMessage();}
System.out.println(list);
return list;
}
}
EDIT:
This my class for testing. My object is an arraylist of custom objects if you need the custom object just comment.
class main {
public static void main(String[] args) {
Date date = new Date();
Book b1 = new Book("abc", "Phi", true, date, null);
Book b2 = new Book("cba", "Someone", true, date, null);
Books booklist = new Books();
booklist.add(b1);
booklist.add(b2);
File filetoDo = new File("book.txt");
//write arraylist into file
writereadFile.writeFile(booklist, filetoDo);
//clear the arraylist
booklist.clear();
//read book from file
writereadFile.readFile(booklist, filetoDo);
System.out.println(booklist);
}
}
Your test should read:
bookList = writereadFile.readFile(booklist, filetoDo);
and, by the way, you should really refactor your readFile method to simply:
public static ArrayList<Object> readFile(File file)
You can't modify the argument reference like that, since Java is always pass-by-value call semantics. (You could modify the list argument contents inside the function, but that's not what you are doing.)
If you are using Java 8 try using Streams:
public static readFile(String filePath) {
List<Object> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.forEach(list::add);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
I'm playing around this topic a bit on my own, so below you can find some code snippets that might help you.
Examples are very short and simple, so I hope you will not just use e.printStackTrace() in your code :)
public class ExternalIO {
private ExternalIO() {
}
public static ObjectOutputStream objectOutputStream(String basePath, String pathToFile) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(createFileIfDoesNotExist(absolutePath(basePath, pathToFile)));
return new ObjectOutputStream(fileOutputStream);
}
public static ObjectInputStream objectInputStream(String basePath, String pathToFile) throws IOException {
FileInputStream fileInputStream = new FileInputStream(absolutePath(basePath, pathToFile));
return new ObjectInputStream(fileInputStream);
}
private static File createFileIfDoesNotExist(String absolutePath) throws IOException {
File file = new File(absolutePath);
if (file.exists()) {
return file;
}
file.getParentFile().mkdirs();
file.createNewFile();
return file;
}
private static String absolutePath(String basePath, String pathToFile) {
return Paths.get(basePath, pathToFile).toAbsolutePath().toString();
}
}
output usage:
List<ItemType> input = null; //create your input list here
try (ObjectOutputStream objectOutputStream = ExternalIO.objectOutputStream(CONFIG, FILENAME)) {
objectOutputStream.writeObject(input);
} catch (Exception e) {
e.printStackTrace();
}
input usage:
try (ObjectInputStream objectInputStream = ExternalIO.objectInputStream(CONFIG, FILENAME)) {
return (List<ItemType>) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
hope that helps ; )
I am writing a program in Java which displays a range of afterschool clubs (E.G. Football, Hockey - entered by user). The clubs are added into the following ArrayList:
private ArrayList<Club> clubs = new ArrayList<Club>();
By the followng Method:
public void addClub(String clubName) {
Club club = findClub(clubName);
if (club == null)
clubs.add(new Club(clubName));
}
'Club' is a class with a constructor - name:
public class Club {
private String name;
public Club(String name) {
this.name = name;
}
//There are more methods in my program but don't affect my query..
}
My program is working - it lets me add a new Club Object into my arraylist, i can view the arraylist, and i can delete any that i want etc.
However, I now want to save that arrayList (clubs) to a file, and then i want to be able to load the file up later and the same arraylist is there again.
I have two methods for this (see below), and have been trying to get it working but havent had anyluck, any help or advice would be appreciated.
Save Method (fileName is chosen by user)
public void save(String fileName) throws FileNotFoundException {
String tmp = clubs.toString();
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
pw.write(tmp);
pw.close();
}
Load method (Current code wont run - File is a string but needs to be Club?
public void load(String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream(fileName);
Scanner scan = new Scanner(fileIn);
String loadedClubs = scan.next();
clubs.add(loadedClubs);
}
I am also using a GUI to run the application, and at the moment, i can click my Save button which then allows me to type a name and location and save it. The file appears and can be opened up in Notepad but displays as something like Club#c5d8jdj (for each Club in my list)
You should use Java's built in serialization mechanism.
To use it, you need to do the following:
Declare the Club class as implementing Serializable:
public class Club implements Serializable {
...
}
This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.
To write your list to a file do the following:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(clubs);
oos.close();
To read the list from a file, do the following:
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
List<Club> clubs = (List<Club>) ois.readObject();
ois.close();
As an exercise, I would suggest doing the following:
public void save(String fileName) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Club club : clubs)
pw.println(club.getName());
pw.close();
}
This will write the name of each club on a new line in your file.
Soccer
Chess
Football
Volleyball
...
I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.
Every class in Java extends the Object class. As such you can override its methods. In this case, you should be interested by the toString() method. In your Club class, you can override it to print some message about the class in any format you'd like.
public String toString() {
return "Club:" + name;
}
You could then change the above code to:
public void save(String fileName) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Club club : clubs)
pw.println(club); // call toString() on club, like club.toString()
pw.close();
}
In Java 8 you can use Files.write() method with two arguments: Path and List<String>, something like this:
List<String> clubNames = clubs.stream()
.map(Club::getName)
.collect(Collectors.toList())
try {
Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
log.error("Unable to write out names", e);
}
This might work for you
public void save(String fileName) throws FileNotFoundException {
FileOutputStream fout= new FileOutputStream (fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(clubs);
fout.close();
}
To read back you can have
public void read(String fileName) throws FileNotFoundException {
FileInputStream fin= new FileInputStream (fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
clubs= (ArrayList<Clubs>)ois.readObject();
fin.close();
}
ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();
Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?
To save and load an arraylist of
public static ArrayList data = new ArrayList ();
I used (to write)...
static void saveDatabase() {
try {
FileOutputStream fos = new FileOutputStream("mydb.fil");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
databaseIsSaved = true;
}
catch (IOException e) {
e.printStackTrace();
}
} // End of saveDatabase
And used (to read) ...
static void loadDatabase() {
try {
FileInputStream fis = new FileInputStream("mydb.fil");
ObjectInputStream ois = new ObjectInputStream(fis);
data = (ArrayList<User>)ois.readObject();
ois.close();
}
catch (IOException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
} // End of loadDatabase
I want to store an object from my class in file, and after that to be able to load the object from this file. But somewhere I am making a mistake(s) and cannot figure out where. May I receive some help?
public class GameManagerSystem implements GameManager, Serializable {
private static final long serialVersionUID = -5966618586666474164L;
HashMap<Game, GameStatus> games;
HashMap<Ticket, ArrayList<Object>> baggage;
HashSet<Ticket> bookedTickets;
Place place;
public GameManagerSystem(Place place) {
super();
this.games = new HashMap<Game, GameStatus>();
this.baggage = new HashMap<Ticket, ArrayList<Object>>();
this.bookedTickets = new HashSet<Ticket>();
this.place = place;
}
public static GameManager createManagerSystem(Game at) {
return new GameManagerSystem(at);
}
public boolean store(File f) {
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(games);
oos.writeObject(bookedTickets);
oos.writeObject(baggage);
oos.close();
fos.close();
} catch (IOException ex) {
return false;
}
return true;
}
public boolean load(File f) {
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
this.games = (HashMap<Game,GameStatus>)ois.readObject();
this.bookedTickets = (HashSet<Ticket>)ois.readObject();
this.baggage = (HashMap<Ticket,ArrayList<Object>>)ois.readObject();
ois.close();
fis.close();
} catch (IOException e) {
return false;
} catch (ClassNotFoundException e) {
return false;
}
return true;
}
.
.
.
}
public class JUnitDemo {
GameManager manager;
#Before
public void setUp() {
manager = GameManagerSystem.createManagerSystem(Place.ENG);
}
#Test
public void testStore() {
Game g = new Game(new Date(), Teams.LIONS, Teams.SHARKS);
manager.registerGame(g);
File file = new File("file.ser");
assertTrue(airport.store(file));
}
}
The solution of this problem is that when you are using other objects, let say class A, into a collection like HashMap and want to serialize the HashMap object, then implement the interface Serializable for class A like this:
class A implements Serializable {
}
...
HashMap<Integer,A> hmap;
...
Otherwise that object will not be serializable.
I hope it will solve this problem now.
Try oos.flush() before you close it.
Please remenber that the whole object graph is persisted during serialize. If you have some references to GUI classes for example, you either have to make them serializable, too, or tag them as "transient", so Java won't serialize them.