public void openFile() throws FileNotFoundException, IOException {//打开一张图
JFileChooser filechooser=new JFileChooser();
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result=filechooser.showOpenDialog(this);
if(result==JFileChooser.CANCEL_OPTION)
return;
File filename=filechooser.getSelectedFile();
filename.canRead();
if(filename==null||filename.getName().equals(""))
JOptionPane.showMessageDialog(filechooser, "文件错误", "文件错误", JOptionPane.ERROR_MESSAGE);
else
try{
FileInputStream fi=new FileInputStream(filename);
ObjectInputStream oi=new ObjectInputStream(fi);
for(myPoint p:drawings) //drawings是一个ArrayList,里面存放的是我的图元,图元定义见后面代码。
p=(myPoint)oi.readObject();
oi.close();
}
catch (EOFException eof) {
JOptionPane.showMessageDialog(this, "文件结束", "文件结束", JOptionPane.ERROR_MESSAGE);
}
catch (ClassNotFoundException cnf) {
JOptionPane.showMessageDialog(this, "不能创建对象", "没有找到类型", JOptionPane.ERROR_MESSAGE);
}
catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "读文件错误", "读文件错误", JOptionPane.ERROR_MESSAGE);
}
repaint();
} public void saveFile() {//保存一张图
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result=fileChooser.showSaveDialog(this);
if(result==JFileChooser.CANCEL_OPTION)return;
File fileName=fileChooser.getSelectedFile();
fileName.canWrite();
if(fileName==null||fileName.getName().equals(""))
JOptionPane.showMessageDialog(fileChooser, "文件错误","文件错误",JOptionPane.ERROR_MESSAGE);
else{
try{
fileName.delete();
FileOutputStream fo=new FileOutputStream(fileName);
ObjectOutputStream oo=new ObjectOutputStream(fo);
for(myPoint p:drawings){
oo.writeObject(p);
oo.flush();
}
oo.close();
fo.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
我的图元定义:public class myPoint implements Serializable{ //myPoint.java文件
private static final long serialVersionUID = 1L;
public int tool;
public int size;
public Color color;
public Point2D sp;
public myPoint(int t,int s,Color c,Point2D p) {
this.sp=p;
this.size=s;
this.color=c;
this.tool=t;
}
.....//相关函数
}
public class myShapes extends myPoint { //继承自myPoint,myShapes.java文件
private static final long serialVersionUID = 1L;
private Point2D ep;
public myShapes(int t,int s,Color c,Point2D p) {
super(t, s,c,p);
ep=p;
}
......//相关函数
}public class myText extends myShapes{ //继承自myPoint,myText.java文件
private static final long serialVersionUID = 1L;
private ArrayList<String> text;
public myText(int t,int si,Color c,Point2D p) {
super(t,si,c, p);
text=new ArrayList<String>();
}
......//相关函数
}
在画板中,我确定一定以及肯定drawings里面不为null,我先保存,保存的时候没有扩展名(事实也应该这样),但是再open的时候就是没有的。
不知道是为什么?求指点~~
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货