Convert Myobject to byte - java

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;
}

Related

How to write serializable object to String without writing to file?

I want to write a class object to the string and then again create an object from it.
I searched on the net but all I found is to write an object to file however I want to write in the string, not on file.
Below is the example of writing to file similarly I want to write in String or similar Object and not in the file.
some_class implements serializable {
...
}
FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(object1);
o.close();
f.close();
FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
// Read objects
some_class object2 = (some_class) oi.readObject();
oi.close();
fi.close();
Please help with the same.
This would be one way:
try
{
// To String
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(object1);
String serializedObject1 = bos.toString();
os.close();
// To Object
ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject1.getBytes());
ObjectInputStream oInputStream = new ObjectInputStream(bis);
YourObject restoredObject1 = (YourObject) oInputStream.readObject();
oInputStream.close();
} catch(Exception ex) {
ex.printStackTrace();
}
I would prefer the Base64 way though.
This would be an example of encoding:
private static String serializableToString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
And this is an example of decoding:
private static Object objectFromString(String s) throws IOException, ClassNotFoundException
{
byte [] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(data));
Object o = ois.readObject();
ois.close();
return o;
}
the best way to serialize an object to String and vice versa you should convert the object into JSON String and encode into base64. and to get object decode base64 and convert to object using GSON (opensource google provide java library)
class foo{ String name, email;
//setter getter
}
convert Object to base64 JSON
public static String convertToJson(Object o){
String result=new Gson().toJson(o);
return Base64.getEncoder().encodeToString(result);
}
//read base64
public static <T> T convertJsonToObject(String base64Object,Class<T> classOfT){
Gson gson = new Gson();
return gson.fromJson(new InputStreamReader(new ByteArrayInputStream(Base64.getDecoder().decode(base64Object))),classOfT);
}
public static void main(String[] args) {
foo obj=new foo("jhon","jhon#gamil.com");
String json=convertToJson(foo);
System.out.println(json);
foo obj_fromJson=convertJsonToObject(json,foo.class);
System.out.println(obj_fromJson.getName());
}

Reading/Writing objects to file returning null

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.

Java Cant read or write object to file

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.

Object Cannot Be Cast to ArrayList

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();
}
}

Save and load SMO weka model from file

I am using Weka SMO to classify my training data and I want to save and load easily to/from file my SMO model. I have created a save method in order to store Classifier to file. My code is the following:
private static Classifier loadModel(Classifier c, String name, File path) throws Exception {
FileInputStream fis = new FileInputStream("/weka_models/" + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
return c;
}
private static void saveModel(Classifier c, String name, File path) throws Exception {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream("/weka_models/" + name + ".model"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
oos.writeObject(c);
oos.flush();
oos.close();
}
My problem is, how to convert ObjectInputStream to Classifier object.
Ok it was an easy one, I ve just had to use readObject.
private static Classifier loadModel(File path, String name) throws Exception {
Classifier classifier;
FileInputStream fis = new FileInputStream(path + name + ".model");
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (Classifier) ois.readObject();
ois.close();
return classifier;
}

Categories