javaobjectoutputstream

java.io.NotSerializableException with ObjectOutputStream


I'm trying to write a Object to file. The results return java.io.NotSerializableException, although I have implemented Serializable

FileHandle.java:

public static void writeFile(File file, Object object) throws IOException {
    ObjectOutputStream output = null;
    FileOutputStream fileOutput = null;
    fileOutput = new FileOutputStream(file);
    output = new ObjectOutputStream(fileOutput);
    output.writeObject(object);
    if (output != null) {
        output.close();
    }
    if (fileOutput != null) {
        fileOutput.close();
    }
}

The Object I want to write: Photo.java

public class Photo implements Serializable{
    private String backgroundUrl;
    private Color textBoxColor = Color.CORAL;
    private Message message = new Message();
    private Watermark watermark = new Watermark();

    public Photo(){
    }

    public Photo(String backgroundUrl, Color textBoxColor, Message message, Watermark watermark){
        this.backgroundUrl = backgroundUrl;
        this.textBoxColor = textBoxColor;
        this.watermark = watermark;
        this.message = message;
    }

    // getter and setter
}

Watermark.java:

public class Watermark implements Serializable{
    private String watermarkUrl;
    private int height = 85;
    private int width = 85;
    private Position position = Position.BOTTOM_RIGHT; // this is ENUM

    public Watermark(){
    }

    public Watermark(String watermarkUrl, Position position){
        this.watermarkUrl = watermarkUrl;
        this.position = position;
    }

    public Watermark(String watermarkUrl, int height, int width, Position position){
        this.watermarkUrl = watermarkUrl;
        this.height = height;
        this.width = width;
        this.position = position;
    }

    // getter and setter
}

Message.java:

public class Message implements Serializable{
    private String content;
    private Color color = Color.WHITE;
    private float size = 30f;

    // getter and setter
}

Position.java:

public enum Position {
    TOP_LEFT(1), TOP_RIGHT(2), BOTTOM_LEFT(3), BOTTOM_RIGHT(4);

    private int value;

    Position(int value){
        this.value = value;
    }

    public int getPosition(){
        return value;
    }
}

I'm guessing the problem derive from the enum, isn't it?


Solution

  • thanks to @user, my code has work. The problem derived from javafx Color, I have convert it to awt Color in model

    public class ColorUtil {
    
        public static Color fxToAwt(javafx.scene.paint.Color color){
            return new Color((float)color.getRed(), (float)color.getGreen(), (float)color.getBlue(), (float)color.getOpacity());
        }
    
        public static javafx.scene.paint.Color awtToFx(Color color){
            return new javafx.scene.paint.Color(color.getRed()/255.0, color.getGreen()/255.0, color.getBlue()/255.0, color.getAlpha()/255.0);
        }
    }