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.
Related
#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.
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 created a custom object of type Task and I want to save it in a binary file in internal storage. Here is the class I created:
public class Task {
private String title;
private int year;
private int month;
private int day;
private int hour;
private int minute;
public Task(String inputTitle, int inputYear, int inputMonth, int inputDay, int inputHour, int inputMinute) {
this.title = inputTitle;
this.year = inputYear;
this.month = inputMonth;
this.day = inputDay;
this.hour = inputHour;
this.minute = inputMinute;
}
public String getTitle() {
return this.title;
}
public int getYear() {
return this.year;
}
public int getMonth() {
return this.month;
}
public int getDay() {
return this.day;
}
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
}
In an activity, I created a method that will save my object to a file. This is the code I used:
public void writeData(Task newTask) {
try {
FileOutputStream fOut = openFileOutput("data", MODE_WORLD_READABLE);
fOut.write(newTask.getTitle().getBytes());
fOut.write(newTask.getYear());
fOut.write(newTask.getMonth());
fOut.write(newTask.getDay());
fOut.write(newTask.getHour());
fOut.write(newTask.getMinute());
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Now I would like to create a method that will extract the data from the file. By reading on the internet, a lot of people use FileInputStream but I have trouble with extracting the bytes from it and knowing how long a String can be. Furthermore, I used a simple method found online but I get permission denied. As I said, I am very new to Android development.
public void readData(){
FileInputStream fis = null;
try {
fis = new FileInputStream("data");
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Any help will be appreciated.
For permission issues, I encourage you to use an external storage such as an SD card.
Environment.getExternalStorageDirectory()
you can create a folder there and save your files. You can also use "/data/local/" if your system permits user files to be saved there.
You can refer to this page regarding the various ways you can save files to internal and external storage,
For the second problem I suggest you to use DataInputStream,
File file = new File("myFile");
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();
You can code something like this,
import java.io.*;
public class Sequence {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
String str="Enter your Age :";
System.out.print(str);
int i=dis.readInt();
System.out.println((int)i);
}
}
You can also Use Serializable interface for reading and writing serializable objects. In fact, I used this once when I tried to write data values directly to files instead of any traditional databases (In my very first undergraduate years, I was not familiar with databases). A good example is here,
import java.io.*;
import java.util.*;
import java.util.logging.*;
/** JDK before version 7. */
public class ExerciseSerializable {
public static void main(String... aArguments) {
//create a Serializable List
List<String> quarks = Arrays.asList(
"up", "down", "strange", "charm", "top", "bottom"
);
//serialize the List
//note the use of abstract base class references
try{
//use buffering
OutputStream file = new FileOutputStream("quarks.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try{
output.writeObject(quarks);
}
finally{
output.close();
}
}
catch(IOException ex){
fLogger.log(Level.SEVERE, "Cannot perform output.", ex);
}
//deserialize the quarks.ser file
//note the use of abstract base class references
try{
//use buffering
InputStream file = new FileInputStream("quarks.ser");
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream (buffer);
try{
//deserialize the List
List<String> recoveredQuarks = (List<String>)input.readObject();
//display its data
for(String quark: recoveredQuarks){
System.out.println("Recovered Quark: " + quark);
}
}
finally{
input.close();
}
}
catch(ClassNotFoundException ex){
fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
}
catch(IOException ex){
fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
}
}
// PRIVATE
//Use Java's logging facilities to record exceptions.
//The behavior of the logger can be configured through a
//text file, or programmatically through the logging API.
private static final Logger fLogger =
Logger.getLogger(ExerciseSerializable.class.getPackage().getName())
;
}
From what I see, you are trying to dump the contents of the object into a file and then read it back. But the way you are doing it now is just writing all the data to the file without any structure, which is a terrible idea.
I would recommend you try to implement the Serializable interface and then just use the writeObject() and readObject() methods.
Alternatively, you could dump the data into an XML file or something that has some structure to it.
Android provides a private directory structure to each application for exactly this kind of data. You don't need special permissions to access it. The only caveat (which is generally a good caveat) is that only your app can access it. (This principle is part of the security that prevents other apps from doing bad things to you.)
If this meets you need for storage, just call getFilesDir() from whatever context is readily available (usually your activity). It looks like in your case you would want to pass the context as a parameter of readData() and writeData(). Or you could call getFilesDir() to get the storage directory and then pass that as the parameter to readData() and writeData().
One other caveat (learned the hard way). Although undocumented, I've found that sometimes Android will create files in this application directory. I strongly recommend that rather than storing files directly in this application folder you instead create your own storage directory in the application directory returned by getFilesDir(), and then store your files there. That way you won't have to worry about other files that might show up, for example if you try to list the files in the storage directory.
File myStorageFolder = new File(context.getFilesDir(), "myStorageFolder");
(I agree with P basak that DataInputStream and DataOutputStream are your best option for reading and writing the data. I disrecommend Serialization except in a very narrow set of applications where transportability is a factor as it is very inefficient. In my case objects that took 15 seconds to load via Serialization loaded in less than 2 seconds using DataInputStream.)
I want to save the contents of my arraylist to a textfile. What I have so far is shown below, however instead of adding x.format("%s%s", "100", "control1"); to the textfile, I want to add objects from an arraylist, how do I go about this?
import java.util.*;
public class createfile
{
ArrayList<String> control = new ArrayList<String>();
private Formatter x;
public void openFile()
{
try {
x = new Formatter("ControlLog.txt");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: Your file has not been created");
}
}
public void addRecords()
{
x.format("%s%s", "100", "control1");
}
public void closeFile()
{
x.close();
}
}
public class complete
{
public static void main(String[] args)
{
createfile g = new createfile();
g.openFile();
g.addRecords();
g.closeFile();
}
}
Both ArrayList and String implement Serializable. Since you have an ArrayList of string you can write it to the file like this:
FileOutputStream fos = new FileOutputStream("path/to/file");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(myArrayList); //Where my array list is the one you created
out.close();
Here is a really good tutorial that shows you how to write java objects to a file.
The written objects can be read back from the file in a similar way.
FileInputStream in = new FileInputStream("path/to/file");
ObjectInputStream is = new ObjectInputStream(in);
myArrayList = (ArrayList<String>) is.readObject(); //Note that you will get an unchecked warning here
is.close()
Here is a tutorial on how to read objects back from a file.
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