ObjectInputStream gives IOException when readObject() is called - java

I'm trying to copy a file with .dat extension from a certain directory decided by the user into the project directory. When I try to read the saved object selected by the user, the program always gives IOException.
File f = new File(chooser.getSelectedFile().getPath());
if(f.exists() && !f.isDirectory()) {
FileInputStream flusso= null;
ObjectInputStream leggiObj=null;
try {
flusso = new FileInputStream(chooser.getSelectedFile().getPath());
System.out.println(chooser.getSelectedFile().getPath());
leggiObj = new ObjectInputStream(flusso);
if (leggiObj.readObject().getClass().equals(DatiProgresso.class)) {
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();//<----THIS LINE GIVES THE EXEPTION
leggiObj.close();
flusso.close();
System.out.println("Ciao");
FileOutputStream fop = new FileOutputStream("salvataggi/" + dp.getNome() + ".dat");
ObjectOutputStream scriviObj = new ObjectOutputStream(fop);
scriviObj.writeObject(dp);
scriviObj.flush();
fop.close();
} else {
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException ex) {
System.out.println("HeadlessException");
ex.printStackTrace();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("IOException");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException");
ex.printStackTrace();
}
}
}
else
{
JOptionPane.showMessageDialog(this, "Unacceptable file", "Error" ,JOptionPane.ERROR_MESSAGE);
}
DatiProgresso dp = (DatiProgresso) leggiObj.readObject();
This line gives the exception.

leggiObj.readObject().getClass().equals(DatiProgresso.class) - here you read your object from the data stream. On next line you attempt to read 2nd object from the stream. If there is no another object then stream fails.

Related

Why is my .bin file being overwritten when I read data from it? (Java)

I made my own data structure called a User. I am trying to store Users in a .bin file using FileInputStream and FileOutputStream. I am successfully storing a single user when a button is pressed, but then when I close the application and go to read my Users and recognize login info, the .bin file turns blank.
I know that the .bin file is not empty after the program closes, but then when I try to read the file I get a EOFException. Here is my code to read objects from the file:
public void loadUsers() {
try {
ObjectInputStream ois = new ObjectInputStream(fi);
boolean endOfFile = false;
while (!endOfFile) {
try {
System.out.println("loaded a user!");
User person = (User) ois.readObject();
Users.addUser(person);
} catch (EOFException e) {
endOfFile = true;
ois.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Here is my code to write objects to the file:
public void storeUser(User person) {
boolean endOfFile = false;
try {
new ObjectInputStream(fi).readObject();
} catch (EOFException e) {
endOfFile = true;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
if (!endOfFile) {
System.out.println("Appending!");
try {
AppendingObjectOutputStream aos = new AppendingObjectOutputStream(fo);
aos.writeObject(person);
aos.flush();
aos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Writing a new file!");
try {
ObjectOutputStream oos = new ObjectOutputStream(fo);
oos.writeObject(person);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AppendingObjectOutputStream is just a small subclass of ObjectOutputStream I made that overwrites writeStreamHeader() so that there is no header placed in my file when try to write more users. I don't think this is related to the problem because I have yet to write a User onto a file with Users already written on it.

How do I resolve the ClassCastException while retrieving an array of objects from a .txt file?

I have created an array of objects of type Employee and i am putting the objects in a .txt file.
Below is the method that accepts Employee objects a parameter and puts it into the .txt file
public void putDataintoFile(Employee[] obj) {
File file = new File("employeedetails.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
}
catch (IOException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
This above method is invoked from a seperate "Execetor class " which then calls my getDataFromFile() method below
public void getDataFromFile() {
System.out.println("Reached HERE");
try {
FileInputStream fin = new FileInputStream("employeedetails.txt");
try {
ObjectInputStream oin= new ObjectInputStream(fin);
try {
Employee e =(Employee)oin.readObject();
System.out.println("Reached HERE");
System.out.println(e.toString());
} catch (ClassNotFoundException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
oin.close();
fin.close();
}
catch (IOException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(EmployeeService1.class.getName()).log(Level.SEVERE, null, ex);
}
}
On executign I get an error which says.
Exception in thread "main" java.lang.ClassCastException: [LMypackage.Employee; cannot
be cast to Mypackage.Employee
at Mypackage.EmployeeService1.getDataFromFile(EmployeeService1.java:225)
at Mypackage.Executor.main(Executor.java:71)
I have implemented Serializable interface in my Employee Classs
Can anyone help me ?
You're writing an array and trying to read a single object.
This is stated in the exception message, which leads to the read/write code, which is fairly obvious despite all the superfluous vertical whitespace.
Also, in general, don't call not-text files .txt.

File writer not typing in file (Java)

I made a program to produce a file with numbers in it
But the program is not typing any thing in the file it created!
This is the code:
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
ModFile=new File(NameText.getText() + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
if(!ModFile.exists()){
try {
ModFile.createNewFile();
System.out.println("Mod file has been created to the current directory");
writer.write(CodesBox.getText());
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i create a random file, i don't see any thing when i open it!
Please help
Thanks Amir for helping but i noticed i should use FileOutputStream and DataOutputStream...
So, i need help again cause the same problem appeared :(
File ModFile =new File(NameText.getText() + ".mod");
try {
FileOutputStream fos = new FileOutputStream(ModFile);
DataOutputStream dos = new DataOutputStream(fos);
int i = Integer.parseInt(CodesBox.getText());
dos.writeInt(i);
// and other processing
} catch (IOException ex) {
Logger.getLogger(ModMakerGui.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try{
dos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
NetBeans said they cannot find the symbol dos at (dos.close();)
Please help me here again
You have to check that file name is present in NameText.getText().
You dont need to create file, if file dont exist FileWriter will create it self.
You should Close file after processing
private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileWriter writer = null;
try {
writer = new FileWriter(ModFile);
writer.write("test..................");
// and other processing
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
to use FileOutputStream and write byte array follow the following code
private static void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {
//check before file name is nt null
File ModFile =new File("somefile" + ".mod");
FileOutputStream writer = null;
String toProcess = "00D0C0DE00D0C0DE F000000000000000";
try {
writer = new FileOutputStream(ModFile);
writer.write(toProcess.getBytes(),0,toProcess.getBytes().length);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to use JOptionPane string for BufferedReader?

I am using a JOptionPane to ask the user for a file, which I then give to BufferedReader. However, my code keeps throwing a FileNotFoundException. Could someone please help me to understand why.
Here is my code...
edit = JOptionPane.showInputDialog("Enter a file to edit");
try {
BufferedReader fIn = new BufferedReader(new FileReader(edit));
String in;
try {
while((in = fIn.readLine()) != null) {
System.out.println(in);
}
fIn.close();
}
catch (IOException ex) {
Logger.getLogger(WordProcessor.class.getName()).log(Level.SEVERE, null, ex);
}
try {
fIn.close();
}
catch (IOException ex) {
Logger.getLogger(WordProcessor.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File does not exist");
}
JOptionPane.showMessageDialog(null, "File does not exist");
Here you should do ex.printStackTrace() it will reveal exact problem.
Note that current directory of program will be one from where it is launched so any relative path should be in relation to that not the source directory..

Get EOFException while reading serialized object in Java

I have two methods, one that serialize the Object, and it works ok:
public void record()throws RecordingException
{
ObjectOutputStream outputStream = null;
try
{
outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
outputStream.writeObject(this);
} catch (FileNotFoundException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
} catch (IOException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
}finally
{
try
{
if (outputStream != null) outputStream.close();
} catch (IOException ex){}
}
}
The problem here when deserializing the object, I get EOFException!:
public final User loadObject(UserType usertype) throws InvalidLoadObjectException
{
ObjectInputStream istream = null;
String path = null;
if (usertype == UserType.EMPLOYEE)
{
path = "data/employee.dat";
}else if (usertype == UserType.CUSTOMER)
{
path = "data/customer.dat";
}else
throw new InvalidLoadObjectException("Object is not a sub class of User");
try
{
istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));
User u = loadObject(istream);
istream.close();
return u;
}catch (EOFException ex)
{
System.out.println(ex.getMessage());
return null;
}catch(Exception ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
{
try
{
return (User) stream.readObject();
} catch (IOException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
} catch (ClassNotFoundException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
I don't know if this is the cause of your problem, but the code that writes the file has a subtle flaw. In the finally block, you close the stream and ignore any exceptions. If the close() method performs a final flush(), then any exceptions thrown in the flush will go unreported.
Try outputStream.flush() before closing your stream in serialization object.
The file was empty, or didn't contain the full serialization of the object.

Categories

Resources