I have a problem, I'd like to serialize an ArrayList with Java to a file.
then I'd like to deserialize it to a new ArrayList and continue to add to the ArrayList.
When I deserialize, it doesn't load in the ArrayList, it just prints the file contents. This is my code:
here is the arraylist class
public class Customers implements Serializable{
ArrayList<Customer> customers = new ArrayList();
ArrayList<Customer> customers2 = new ArrayList();
public void add(Customer customerIn) {
customers.add(customerIn);
}
public void remove(Customer customerIn) {
customers.remove(customerIn);
}
public Customer findByName(String firstName, String address) {
//För varje Customer i customers
for (Customer customer : customers) {
if (firstName.equals(customer.getName())) {
if (address.equals(customer.getAddress())) {
return customer;
}
}
}
return null;
}
class for seriallize and deserialize
public class file {
public void saveObjectsToFile(Customers customers) {
try{
FileOutputStream fos= new FileOutputStream("a.listFile");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(customers);
oos.close();
fos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
public void takeOutObjectFromFile(Customers customers) {
try
{
FileInputStream fis = new FileInputStream("a.listFile");
ObjectInputStream ois = new ObjectInputStream(fis);
customers = (Customers) ois.readObject();
ois.close();
fis.close();
//
System.out.println(customers);
}catch(IOException ioe){
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
c.printStackTrace();
return;
}
}
class for customer
//klass customer startar här.
public class Customer implements Serializable{
//Variabler int och String för kund id, namn, adress och telefon.
int CustomerID;
String customerName, customerAddress, customerPhone, Order;
//Konstruktor för klassen
public Customer(String Name, String Address, String Phone, String Order) {
this.customerName = Name;
this.customerAddress = Address;
this.customerPhone = Phone;
this.CustomerID = 100001;
this.Order = Order;
}
//Hämtar och sätter personuppgifter.
public String getName() { return this.customerName; }
public String getAddress() { return this.customerAddress; }
public String getPhone() { return this.customerPhone; }
public int getID() { return this.CustomerID; }
public String getOrder() { return this.Order; }
//Skriver ut kontroll av personuppgifter.
public void printPerson() {
System.out.println("\n\nKONTROLL AV UPPGIFTER\n");
System.out.println("Namn:\t\t\t" + getName());
System.out.println("Adress:\t\t\t" + getAddress());
System.out.println("Telefonnummer:\t\t" + getPhone());
System.out.println("KundID:\t\t\t" + getID());
System.out.println("Order:\t\t\t" + getOrder());
}
public String toString() {
return getName() + " " + getAddress() + " " + getPhone();
}
}
The problem is with this method:
public void takeOutObjectFromFile(Customers customers) {
...
customers = (Customers) ois.readObject();
...
}
You've simply overwritten a local variable. What you should have is:
public Customers takeOutObjectFromFile() {
...
return (Customers) ois.readObject();
...
}
(Also use try-with-resource to ensure you have closed the files in all cases.)
I solved my problem!
Now i can edit my Customers! Thanks for all the help and advice.
public class file {
// Get all persons in file
public List<Customers> getAllPersons(String fileLocation) {
List<Customers> localPersons = new ArrayList<>();
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
localPersons.add((Customers) ois.readObject());
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPersons;
}
// Get person on personId in file
public Customers getPersonOnPersonId(String fileLocation, int personId) {
Customers localPerson = null;
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(personId == tempPerson.getPersonId()) {
localPerson = tempPerson;
break;
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPerson;
}
// Get persons on firstname in file
public List<Customers> getPersonsOnFirstName(String fileLocation, String firstName) {
List<Customers> localPersons = new ArrayList<>();
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(firstName.equals(tempPerson.getFirstName())) {
localPersons.add(tempPerson);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPersons;
}
// Get persons on lastname in file
public List<Customers> getPersonsOnLastName(String fileLocation, String lastName) {
List<Customers> localPersons = new ArrayList<>();
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(lastName.equals(tempPerson.getLastName())) {
localPersons.add(tempPerson);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPersons;
}
// Insert person in file
public void insertPerson(String fileLocation, Customers person) {
List<Customers> localPersons = new ArrayList<>();
// Select block ************************************************
int maxPersonId = 0;
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
localPersons.add(tempPerson);
if(maxPersonId < tempPerson.getPersonId()) {
maxPersonId = tempPerson.getPersonId();
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
// *************************************************************
// Set primary key value to the person block *******************
if(localPersons.isEmpty()) {
person.setPersonId(1);
} else {
maxPersonId++;
person.setPersonId(maxPersonId);
}
// *************************************************************
// Insert block ************************************************
try {
File f = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
localPersons.add(person);
for(Customers p : localPersons) {
oos.writeObject(p);
}
} catch (FileNotFoundException fileNotFoundException) {
System.out.println(fileNotFoundException.getMessage());
} catch (IOException ioexception) {
System.out.println(ioexception.getMessage());
}
// *************************************************************
}
// Update person in file
public void updatePerson(String fileLocation, Customers person) {
List<Customers> localPersons = new ArrayList<>();
// Select block ************************************************
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(person.getPersonId() != tempPerson.getPersonId()) {
localPersons.add(tempPerson);
} else {
localPersons.add(person);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
// *************************************************************
// Insert block ************************************************
try {
File f = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
for(Customers p : localPersons) {
oos.writeObject(p);
}
} catch (FileNotFoundException fileNotFoundException) {
System.out.println(fileNotFoundException.getMessage());
} catch (IOException ioexception) {
System.out.println(ioexception.getMessage());
}
// *************************************************************
}
// Delete person in file
public void deletePerson(String fileLocation, int personId) {
List<Customers> localPersons = new ArrayList<>();
// Select block ************************************************
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(personId != tempPerson.getPersonId()) {
localPersons.add(tempPerson);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
// *************************************************************
// Insert block ************************************************
try {
File f = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
for(Customers p : localPersons) {
oos.writeObject(p);
}
} catch (FileNotFoundException fileNotFoundException) {
System.out.println(fileNotFoundException.getMessage());
} catch (IOException ioexception) {
System.out.println(ioexception.getMessage());
}
// *************************************************************
}
}
This is because your arralylist is being initialized again
change it to private static final this will make your day
private static final ArrayList<Customer> customers = new ArrayList();
Related
Please consider these codes: Is it possible to use FileWriter and FileReader with object of class student?
Student s1 = new Student();
s1.input();//I want to write this method in a File
FileWriter out2 = new FileWriter("input.txt");
out2.write();
out2.flush();
out2.close();
s1.display();//I want to Read this method in a File
FileReader in2 = new FileReader("input.txt");
in2.read();
in2.close();
Yes, you can save any Object you like with FileOutputStream and get it with FileInputStream (as Object, you need casting after this). Just try it out.
As an example:
FileOutputStream fos = null;
ObjectOutputStream writer = null;
Student data = new Student();
try{
fos = new FileOutputStream(fileName);
writer = new ObjectOutputStream(fos);
writer.writeObject(data);
}
catch (IOException ex){
ex.printStackTrace();
}
Just remember closing it and doing the exception exercise :-).
Since I found an old full-working example-class you may want have a look into it (that's pretty ugly code, but it does the job):
import java.io.*;
public class Test {
static boolean checkFile(File file) {
if (file != null) {
if(file.isFile()){
return true;
}
try {
file.createNewFile();
} catch (IOException e) {
System.err.println("Error creating " + file.toString());
}
if (file.isFile() && file.canWrite() && file.canRead())
return true;
}
return false;
}
static boolean writeFile(String dat, Object data){
FileOutputStream fos = null;
ObjectOutputStream writer = null;
try{
fos = new FileOutputStream(dat);
writer = new ObjectOutputStream(fos);
writer.writeObject(data);
}
catch (IOException ex){
ex.printStackTrace();
return false;
}
finally{
try{
if(writer!=null){
writer.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
try{
if(fos!=null){
fos.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
return true;
}
static Student readFile(String dat){
FileInputStream fis = null;
ObjectInputStream reader = null;
Student student = null;
try{
fis = new FileInputStream(dat);
reader = new ObjectInputStream(fis);
student = (Student) reader.readObject();
}
catch (Exception ex){
ex.printStackTrace();
}
finally{
try{
if(reader!=null){
reader.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
return student;
}
public static void main(String[] args){
Student student = new Student("Horst");
String filename = "input.txt";
boolean worked = false;
if(checkFile(new File(filename)))
worked=writeFile(filename, student);
student = new Student("not Horst");
if(worked)
student= (Student) readFile(filename);
System.out.println("Student : " + student.name);
}
}
class Student implements Serializable{
public String name;
public Student(String name){
this.name=name;
}
}
I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}
List ll=new LinkedList();
Student temp;
int size = obj.readInt();
System.out.println(size);
for (int i = 0; i <size; ++i) {
ll.add((Student) obj.readObject());
}
obj.close();
System.out.println(ll);
}
it causes the run time exception as
"Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at p1.DeSerializeDemo1.main(DeSerializeDemo1.java:18)"
Please give me solution for this.
EOFException in ObjectInputStream.readInt means that there are less than 4 bytes left in the file after current position.
Just handle the Exception
try{
int size = obj.readInt();
}catch(EOFException ex){}
Why don't you create a class and save/load the entire object (that class needs to implement Serializable though (and all objects used it that class too)), then get the information you want using that object you can cast it afterwards:
public static Object load(String path) throws FileNotFoundException, Exception {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))) {
final Object result = ois.readObject();
ois.close();
return result;
}
}
public static void save(Object obj, String path) throws Exception {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
oos.writeObject(obj);
oos.flush();
oos.close();
}
}
Exception cause is that you are not calling ObjectOutputStream.writeInt(int) before writing objects. As far as I understand you are trying to store number of objects, which is stored in the file. So, you should do it like this: obj.writeInt(2);
public class Test implements Serializable {
private static final long serialVersionUID = 243705916609512381L;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
Test s = new Test();
s.setName("Test");
Test s1 = new Test();
s1.setName("Test 2");
ObjectOutputStream oos = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
ObjectInputStream ois = null;
try {
fileOutputStream = new FileOutputStream("C:\\test.txt");
oos = new ObjectOutputStream(fileOutputStream);
oos.writeInt(2);
oos.writeObject(s1);
oos.writeObject(s);
oos.flush();
oos.close();
fileOutputStream.close();
fileInputStream = new FileInputStream("C:\\test.txt");
ois = new ObjectInputStream(fileInputStream);
int readInt = ois.readInt();
System.out.println("Read int " + readInt);
Test readObject = (Test) ois.readObject();
System.out.println(readObject.getName());
Test readObject2 = (Test) ois.readObject();
System.out.println(readObject2.getName());
ois.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// close everything
}
}
I want my app to store multiple objects locally for later use.
Now, my problem is that I know how to load an object from an ObjectInputStream by taking the entire file(federations.dat). Is there a way for me to load say object WHERE id = N from "federations.dat" ? Or do I have to create separate files for each object?
This is my load method:
public static Object load(Context ctx, String filename) throws FileNotFoundException
{
Object loadedObj = null;
InputStream instream = null;
instream = ctx.openFileInput(filename);
try {
ObjectInputStream ois = new ObjectInputStream(instream);
loadedObj = ois.readObject();
return loadedObj;
} catch (StreamCorruptedException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any suggestions come to mind ?
You can use it like this..
ArrayList<Object> arrayList = new ArrayList<Object>();
Object obj = null;
while ((obj = ois.readObject()) != null) {
arrayList.add(obj);
}
You can return an ArrayList on your method.
return arrayList;
Edit:
Full code would be like this..
public static ArrayList<Object> load(Context ctx, String filename)
{
InputStream fis = null;
ObjectInputStream ois = null;
ArrayList<Object> arrayList = new ArrayList<Object>();
Object loadedObj = null;
try {
fis = ctx.openFileInput(filename);
ois = new ObjectInputStream(fis);
while ((loadedObj = ois.readObject()) != null) {
arrayList.add(loadedObj);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != ois) ois.close();
if (null != fis) fis.close();
}
return arrayList;
}
Hope it helps..
An extention to #Jan 's code, fixing the problem of keeping ois open if an exception is thrown, along with some minor issues.
public static ArrayList<Object> load(Context ctx, String filename) throws FileNotFoundException {
InputStream instream = ctx.openFileInput(filename);
ArrayList<Object> objects = new ArrayList<Object>();
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try{
Object loadedObj = null;
while ((loadedObj = ois.readObject()) != null) {
objects.add(loadedObj);
}
return objects;
}finally{
ois.close();
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
So basically, what I'm trying to do is to read from my database MySQL through a server I have created. I put the info from my database in an ArrayList, but the client can't read it. When I add simple Strings, it works. But not when its from my database. Any solutions?
public class Server implements Runnable {
private ServerSocket server;
private Socket socket;
private ObjectOutputStream oos = null;
public Server() {
try {
server = new ServerSocket(4444);
new Thread(this).start();
} catch (Exception e) {
System.out.println(e);
}
}
public void run() {
System.out.println("Server running");
while (true) {
try {
socket = server.accept();
sayHi();
System.out.println("Hallå");
} catch (Exception e) {
}
}
}
private void sayHi(){
DataOutputStream dos;
try {
dos = new DataOutputStream(socket.getOutputStream());
oos = new ObjectOutputStream(socket.getOutputStream());
dos.writeUTF("Hej");
sendNames();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendNames() {
ArrayList<String> drinkar = new ArrayList<String>();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "drycker";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = (Statement) con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM drinktable");
while (res.next()) {
String s = res.getString("Name");
for(int i = 0; i<drinkar.size(); i++){
drinkar.add(s);
}
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
ArrayList<String> a = new ArrayList<String>();
a.add("Hejsan");
a.add("Svejsan");
try {
FileOutputStream fos = new FileOutputStream("randomList");
oos = new ObjectOutputStream(fos);
oos.writeObject(drinkar);
oos.flush();
oos.reset();
oos.close();
fos.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
public class Client implements Runnable {
private Socket socket;
private DataInputStream dis;
private ObjectInputStream ois = null;
public Client() {
socket = new Socket();
InetSocketAddress ipPort = new InetSocketAddress("192.168.0.10", 4444);
try {
socket.connect(ipPort);
dis = new DataInputStream(socket.getInputStream());
ois = new ObjectInputStream(socket.getInputStream());
} catch (Exception e) {
}
new Thread(this).start();
}
public void run() {
while (true) {
try {
String msg = dis.readUTF();
if (msg.equals("Hej")) {
Thread.sleep(50);
receiveArrayList();
}
} catch (Exception e) {
}
}
}
public void receiveArrayList() {
try {
FileInputStream fis = new FileInputStream("randomList");
ois = new ObjectInputStream(fis);
ArrayList<String> a= (ArrayList<String>) (ois.readObject());
for(int i = 0; i < a.size(); i++){
System.out.println((String)a.get(i));
}
ois.close();
} catch (ClassNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
new Client();
}
}