【发布时间】:2015-11-20 15:36:37
【问题描述】:
我正在尝试将对象写入文件。结果返回java.io.NotSerializableException,虽然我已经实现了Serializable
文件句柄.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();
}
}
我要写的对象: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
}
位置.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;
}
}
我猜问题源于枚举,不是吗?
【问题讨论】:
-
什么是
Color.CORAL?您应该检查整个异常文本。根据您发布的 sn-ps,序列化工作(使用 Color.BLUE)。 -
你的代码看起来不错,也许你可以把整个项目上传到 github 上?并提供详细的stacktrace
-
Color.CORAL 是取自 javafx 的吗?这可能会引发异常,因为 javafx Color 没有实现 Serializable。见docs.oracle.com/javafx/2/api/javafx/scene/paint/Color.html
-
我只是尝试获取完整的堆栈跟踪。它表明 javafx 中的 Color 对象不可序列化:
-
是的@user
java.io.NotSerializableException: javafx.scene.paint.Color。也许我会尝试将其转换为 awt Color