There is this method klasOpslaan(Klas deKlas). I need to write deKlas to an object. Afterwards I need to read it with method klasInladen. I am getting an error writing aborted; java.io.NotSerializableException: week5.practicum4.Klas although I implemented Serializeable. I did note that when writing my object it makes the object but doesn't write to it. I did implement everything but StackOverflow wont let me post it.
public class KlasManager implements Serializable {
public void klasOpslaan(Klas deKlas) throws IOException, FileNotFoundException {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Klas opgeslassgen");
oos.writeObject(deKlas);
oos.close();
}
public Klas klasInladen() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Klas deKlas = (Klas) ois.readObject();
ois.close();
return deKlas;
}
}
edit: needed Serializeable in other classes, not in this one.
Related
I have run SAST in my codebase and got some Medium severity alerts in the Checkmarx scan and few of them states 'Unclosed_Objects' . I am not understanding this issue. Any pointers will help me.
This is giving alerts in this section of the code. All the close() methods.
public Object deepCopy(final Object value) throws HibernateException {
try {
// use serialization to create a deep copy
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(value);
oos.flush();
oos.close();
bos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray());
Object obj = new ObjectInputStream(bais).readObject();
bais.close();
return obj;
} catch (ClassNotFoundException | IOException ex) {
throw new HibernateException(ex);
}
I'm trying to read and write objects into a file. Reading the output into a new object works, but every value is null.
Here's the code:
public void read() throws Exception
{
try
{
FileInputStream fIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fIn);
Object obj = in.readObject();
System.out.println(obj);
public void save() throws Exception
{
FileOutputStream fOut = new FileOutputStream(file.toString());
ObjectOutputStream out = new ObjectOutputStream(fOut);
out.writeObject(this);
out.flush();
out.close();
}
Here is the file output: (image of output)
I'd like to receive the values I previously wrote to the file in the new object created, however all I get is null for all values.
Edit: since people are asking for the entire class, and I have no idea what code could be causing what, here's the entire UserFile class: https://pastebin.com/Gr1tcGsg
I have ran that code and it works which means you most likely read before you write or you got an exception such as InvalidClassException: no valid constructor which would make sense in your case.
The code I ran:
public class SavedObject implements Serializable
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
new SavedObject();
}
private final int random;
private SavedObject() throws IOException, ClassNotFoundException
{
random = ThreadLocalRandom.current().nextInt();
File file = new File("Object.txt");
save(file);
read(file);
}
private void save(File file) throws IOException
{
FileOutputStream fileOutput = new FileOutputStream(file);
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(this);
objectOutput.close();
fileOutput.close();
System.out.println(this);
}
private void read(File file) throws IOException, ClassNotFoundException
{
FileInputStream fileInput = new FileInputStream(file);
ObjectInputStream objectInput = new ObjectInputStream(fileInput);
Object obj = objectInput.readObject();
System.out.println(obj);
objectInput.close();
fileInput.close();
}
public String toString()
{
return "SavedObject(Random: " + random + ")";
}
}
Which prints:
SavedObject(Random: -2145716528)
SavedObject(Random: -2145716528)
Also a few tips for you:
Don't have a try-catch if you throws
Have more readable variable names
Send more code in your next question
ObjectOutputStream is not recommended, if you can, you should write the values as they are
Don't use throws "Exception" instead use throws "
Put the file in instead of file.toString()
I found the problem, it was that in my constructor I wasn't correctly applying the retrieved info from the file. Thanks for everyone's help.
I'm having some trouble with reading an arraylist from file in Java.
I have a "User" class which implements Serializable, so when I go to save an ArrayList of these users it seems to work fine - but when I try read them it's a different story.
ava.lang.ClassCastException: User cannot be cast to java.util.ArrayList
The Code I have for reading in is as follows ..
private List<User> userList = new ArrayList<User>();
public void readList() throws FileNotFoundException, IOException, ClassNotFoundException
{
System.out.println("Trying to read list..");
FileInputStream fis = new FileInputStream("userList.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Created Streams....");
userList = ((ArrayList<User>)ois.readObject());
ois.close();
}
Has anyone has similar problems or know how to help me out?
Thanks.
If you want to deserialize an ArrayList out of the stream, then you must be sure to serialize an ArrayList into the stream. The way you've serialized your User objects, you would be required to deserialize them like so:
private List<User> userList;
public void readList() throws FileNotFoundException, IOException, ClassNotFoundException {
System.out.println("Trying to read list..");
this.userList = new ArrayList<User>();
FileInputStream fis = new FileInputStream("userList.txt");
try {
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Created Streams....");
// you would want to store this number in your object stream as userList.size()
int numberOfUsersSerialized = 5;
for (int i = 0; i < numberOfUsersSerialized; i++) {
userList.add((User) ois.readObject());
}
} finally {
fis.close();
}
}
Hi If a class cannot implement serializable interface and if we try to serialize it, we should get a NotSerializableException. Here I am not getting it. The Cat class doesn't implement Serializable and I try to serialize it. Compiled and run fine why?
import java.io.*;
class Cat{}
class MyTest{
public static void main(String a[]){
Cat c = new Cat();
try{
FileOutputStream fos = new FileOutputStream("test.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(c);
oos.close();
fos.close();
}
catch(Exception e){e.getMessage();}
try{
FileInputStream fis = new FileInputStream("test.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (Cat)ois.readObject();
ois.close();
fis.close();
}
catch(Exception e){e.getMessage();}
}
}
It is throwing exceptions, you are just swallowing them with
catch(Exception e){e.getMessage();}
which just calls a method that returns a String, it doesn't log anything.
Use
e.printStackTrace();
I want to object AuditContainer convert to byte and then save in file:
public class AuditContainer implements Serializable {
private Paint mPaint;
private Path mPath;
private int x,y;
private String text;
boolean is_text;
Problem is because Paint and Path must be serialized, but it cant..
Firstly i want make serialization for this class, but i have got one truble, i cant save all things which i need.
My question is how i can convert AuditoContainer to byte? Is it Posible? and which is princips/options for save my class in file/database?
I need help, please.
If what you want is to write the status of the object to a file, is better if you don't use serialization. Serialization has lots of flaws and is hard to get it done correctly, while you can save the properties of your object easily as strings in the file.
want serialization example ?
ok here is one (make sure that all your Objects mentioned in your variables are serializable as well)
public void save(AuditContainer auditContainer, File file) throws FileNotFoundException, IOException {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(auditContainer);
}finally{
if(oos != null){
oos.flush();
oos.close();
}
}
}
public AuditContainer load(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
AuditContainer auditContainer = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try{
fis = new FileInputStream(file);
ois = new ObjectInputStream(ois);
auditContainer = (AuditContainer)ois.readObject();
}finally{
if(ois != null){
ois.close();
}
}
return auditContainer;
}