I have 3 objects written in the file. The program outputs these 3 objects and then this java.io.EOFException error.
writing to file:
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))) {
planes.sort(Comparator.comparingInt(plane -> plane.productionYear));
planes.forEach(plane -> {
try {
objectOutputStream.writeObject(plane);
} catch (IOException e) {
e.printStackTrace();
}
});
objectOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
reading the file:
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
Object o;
while ((o = objectInputStream.readObject()) != null ){
if (o.getClass().getName().contains("Plane")) {
Plane plane = (Plane) o;
plane.productionYear = plane.productionYearCopy;
plane.speed = plane.speedCopy;
plane.engine = plane.engineCopy;
System.out.println(plane);
} else {
Ship ship = (Ship) o;
ship.productionYear = ship.productionYearCopy;
ship.speed = ship.speedCopy;
ship.engine = ship.engineCopy;
}
}
} catch (Exception e) {
e.printStackTrace();
}
Related
So I am new in programing and i adding a feature in my app which save all sharedpreference key in value in Device internal data folder by using fileoutputStream like this add all data in map and store in jsonobject
private String maptojson(){
Map<String, ?> map = prf.getAll();
JSONObject object = new JSONObject();
for (Map.Entry<String,?> entry : map.entrySet()){
try {
object.put( entry.getKey(), entry.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return object.toString();
}
Now Use FileOutputStream for write file in internal Storage "data'
public void backupSetting() {
Throwable th;
FileOutputStream fileOutputStream;
IOException e;
FileOutputStream fileOutputStream2 = null;
File externalStorageDirectory = Environment.getExternalStorageDirectory();
if (externalStorageDirectory.exists() && externalStorageDirectory.canWrite()) {
if (externalStorageDirectory.getUsableSpace() >= 1048576) {
File file = new File(externalStorageDirectory.toString() + "/data/MyApp/" + "MyAppSetting.ma");
try {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(maptojson().getBytes());
fileOutputStream.flush();
fileOutputStream.close();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} catch (IOException e3) {
e = e3;
try {
e.printStackTrace();
if (fileOutputStream != null) {
}
} catch (Throwable th2) {
th = th2;
fileOutputStream2 = fileOutputStream;
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e4) {
e4.printStackTrace();
throw th;
}
}
throw th;
}
}
} catch (IOException e5) {
e = e5;
fileOutputStream = null;
e.printStackTrace();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
e6.printStackTrace();
}
}
} catch (Throwable th3) {
th = th3;
if (fileOutputStream2 != null) {
}
try {
throw th;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Now i want to add restore setting means restore setting by using that file "MyAppSetting.ma". I know i can do it by using FileInputStream but I don't understand how to do? please help if you could
I am trying to read objects from a file(same objects of a class), using Serializable, but whenit reads all objects it gives me error IOException, java.io.ObjectInputStream$BlockDataInputStream.peekByte.
I am reading objects and then saving to list. But as it reached lets say EOF it throws error.
Here is my method:
private static void updateBook(String name) {
// TODO Auto-generated method stub
FileInputStream fis = null;
ObjectInputStream in = null;
Object obj = new Object();
List<Object> libb = new ArrayList<Object>();
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} finally {
in.close();
//fis.close();
}
for(int j = 0; j < libb.size(); ++j) {
Book li = new Book();
li = (Book) libb.get(j);
System.out.println(li.getBookName());
}
//
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not Exist!");
}
}
Can anyone please tell me how to avoid this error from while(true).
Complete error:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
On your try statement you are missing the catch clause for the EOFException:
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} catch (EOFException eofe) {
// treat it as you like
} finally {
in.close();
//fis.close();
}
you should add:
catch (EOFException e){
// do stuffs
}
as EOFException is not being caught.
I want to maintain database of users of a Bank for my project. I am able to save the number of users in one serializable file. But when I try to save the user to database it adds only the latest one to database.
Below is the sneak peak of code which writes the objects:
if(e.getSource()==submit) {
if(uFName != null && uLName != null && uInitialDeposit !=0) {
if(uAccountType=="Savings") {
Random randomGenerator = new Random();
//Gets the number of users from file if file exists
File f = new File(fileNameAdmin);
if(f.exists() && !f.isDirectory()) {
admin=db.readFromAdminDatabase();
}
u[admin.numberOfUsers]= new User();
u[admin.numberOfUsers].fName=uFName;
u[admin.numberOfUsers].lName=uLName;
u[admin.numberOfUsers].initalDeposit=uInitialDeposit;
u[admin.numberOfUsers].interestRate=uInterestRate;
u[admin.numberOfUsers].accountType="Saving";
u[admin.numberOfUsers].accountNumber=690000+admin.numberOfSavingsAccount;
//Generates a 4 digit random number which will be used as ATM pin
u[admin.numberOfUsers].atmPin=randomGenerator.nextInt(9999-1000)+1000;
//A savings account will be created
sa[admin.numberOfSavingsAccount]=new SavingsAccount(u[admin.numberOfUsers].accountNumber,u[admin.numberOfUsers].fName,u[admin.numberOfUsers].lName,
u[admin.numberOfUsers].initalDeposit,
u[admin.numberOfUsers].interestRate);
u[admin.numberOfUsers].sa=sa[admin.numberOfSavingsAccount];
System.out.println(u[admin.numberOfUsers].sa.balance);
JOptionPane.showMessageDialog(submit,"Congratulations! You are now a member of Symbiosis Bank."
+ "\nYour account number is "+u[admin.numberOfUsers].accountNumber
+" and your ATM Pin is "+u[admin.numberOfUsers].atmPin,"Account Created",JOptionPane.INFORMATION_MESSAGE);
try {
//for(int j = 0; j<admin.numberOfUsers; j++)
db.addUserToDatabase(u[admin.numberOfUsers]);
admin.numberOfSavingsAccount++;
admin.numberOfUsers++;
db.updateAdminDatabase(admin);
dispose();
setVisible(false);
//Welcome welcome = new Welcome();
//welcome.setVisible(true);
InitialInput back = new InitialInput();
back.setVisible(true);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
The database class which has functions to write to database:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Database implements Serializable {
String fileName = System.getProperty("user.home")+"/db.ser";
String fileNameAdmin = System.getProperty("user.home")+"/admindb.ser";
public void addUserToDatabase(User u){
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(u);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("finally")
public User readFromUserDatabase() {
FileInputStream fis;
User temp = null;
try {
fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (User)ois.readObject();
//System.out.println(temp.fName);
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
return temp;
}
}
public void updateAdminDatabase(Administrator admin) {
FileOutputStream fos;
try {
fos = new FileOutputStream(fileNameAdmin);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(admin);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("finally")
public Administrator readFromAdminDatabase() {
FileInputStream fis;
Administrator temp = null;
try {
fis = new FileInputStream(fileNameAdmin);
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (Administrator)ois.readObject();
//System.out.println(temp.fName);
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
return temp;
}
}
}
The code which is trying to read the database:
public void actionPerformed(ActionEvent e) {
if(e.getSource()==deposit) {
//Ask the amount to deposit
int userAmountToDeposit;
try {
for(int i = 0; i<=admin.numberOfUsers; i++) {
u[i] = db.readFromUserDatabase();
System.out.println(u[i].accountNumber);
}
for(int j =0; j<=admin.numberOfUsers; j++) {
if(u[j].accountNumber==userAccountNumber) {
if(u[j].atmPin==userPin) {
u[j].accountBalance=u[j].sa.balance;
u[j].sa.deposit(10);
u[j].accountBalance=u[j].sa.balance;
System.out.println(u[j].accountBalance);
}
}
}
}
Inorder to write and read multiple objects please try as below
Writing multiple object into List
WriteObject wo=new WriteObject(20, "Mohan");
WriteObject wo1=new WriteObject(21, "Mohanraj");
ArrayList<WriteObject> woi=new ArrayList<>();
try {
FileOutputStream fop=new FileOutputStream("c://object.ser");
ObjectOutputStream oos=new ObjectOutputStream(fop);
woi.add(wo);
woi.add(wo1);
oos.writeObject(woi);
} catch NotFoundException e) {
}
Reading all objects from file
try {
FileInputStream fis=new FileInputStream("C://object.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
WriteObject wo=null;
WriteObject[] woj=new WriteObject[5];
ArrayList<WriteObject> woi=new ArrayList<>();
woi=(ArrayList<WriteObject>)ois.readObject();
for(int i=0;i<woi.size();i++){
woi.get(i).getvalues();
}
Here getvalues() is method present in Writeobject class. Follow the same mechanism for your code snippet
If you want to fix it rapidly, you can create a list and store first and foremost your objects in the list (may be ArrayList or List), and then you'll save this list on your file. That is the nice method. Make sure that your objects are serializable.
below, listeVoitures is a stactic variable that will contain all
object that i'm going to retrive from file.
public static void saveVehiculeInFile(ArrayList vehiculeList) {
ObjectOutputStream ous = null;
//ArrayList<Vehicule> listVehiculeToSave = new ArrayList<>();
try {
ous = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File("garage.txt"))));
try {
ous.writeObject(vehiculeList);
System.out.println("\t=====> Les vehicules *** ont été ajouter dans le garage.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ous != null) {
try {
ous.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This method below is for retrive data from file
public static void readVehiculeFromFile() {
ObjectInputStream ins = null;
ArrayList<Vehicule> v = null;
try {
ins = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File("PoweredGarage.txt"))));
try {
v = (ArrayList<Vehicule>)ins.readObject();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (Vehicule vehicule : v) {
listeVoitures.add(vehicule);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I saw people were closing the scanner and getting this. but in my case the used code is:
BlobDomain blobDomain = null;
OutputStream out = null;
try {
blobDomain = new BlobDomain();
out = blobDomain.getBinaryOutputStream();
if (status != null){
fullText = new Scanner(in).useDelimiter("\\A").next();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null)
try {
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
Exception:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
I have a little problem with my Client-Server Application. When I want to connect more than 1 Client and send smth, or I make logout in my Client and try to connect one more time I got Exception:
"java.io.StreamCorruptedException: invalid type code: 04"
What's the problem? Thank's for help.
Server Code:
class ClientCommunication implements Runnable {
private Socket incoming;
public ClientCommunication(Socket clientSocket) {
incoming = clientSocket;
}
public void run() {
try {
synchronized (this) {
serverObjectOutput = new ObjectOutputStream(
incoming.getOutputStream());
serverObjectInput = new ObjectInputStream(
incoming.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
int operation = -1;
synchronized(this) {
while (true) {
try{
if(serverObjectInput.available() > 0){
operation = serverObjectInput.readInt();
switch(operation) {
case 1:
Employee employee = (Employee) serverObjectInput.readObject();
//CHECK LOGGING DATA
// SEND RESULT = 1 OR RESULT = -1
break;
}
}
} catch(IOException | ClassNotFoundException | SQLException ex)
{
ex.printStackTrace();
}
}
}
}
}
class ServerStart implements Runnable {
private int portNumber;
public ServerStart(int portNumber) {
this.portNumber = portNumber;
}
public void run() {
try {
conn = getConnection();
stat = conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
Socket incoming = serverSocket.accept();
Runnable r = new ClientCommunication(incoming);
Thread t = new Thread(r);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Function:
public void actionPerformed(ActionEvent e) {
if (isConnected == false) {
String ServerIP = ip.getText().trim();
int ServerPort = Integer
.parseInt(port.getText().trim());
try {
ClientSocket = new Socket(ServerIP, ServerPort);
clientObjectInput = new ObjectInputStream(
ClientSocket.getInputStream());
clientObjectOutput = new ObjectOutputStream(
ClientSocket.getOutputStream());
isConnected = true;
} catch (IOException ex) {
ex.printStackTrace();
}
synchronized (this) {
try {
ClientLoginFrame login = new ClientLoginFrame();
Employee employee = login.getEmployee();
clientObjectOutput.writeInt(1);
clientObjectOutput.flush();
clientObjectOutput.writeObject(employee);
int result = clientObjectInput.readInt();
if(result == 1)
{
// DO SMTH
}
else {
isConnected = false;
ClientSocket.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
I suspect your problem is that you are sharing the singletons serverInputStream and serverOutputStream between connections. This isn't a problem until you have more than one at which point using the same stream in multiple threads at once corrupts the stream (or makes reading it invalid)