我刚刚用 Java 制作了我的第一个基于 I/O 的东西。我想检查写入文件的内容是否正确保存。为此我编写了以下代码..
import java.io.*;
public class check implements Serializable {
//Make two variables and methods to initialise them
private int height;
private int width;
public void setWidth(int w){
width = w;
}
public void setHeight(int h){
height = h;
}
public static void main(String[] args) {
check obj = new check();
obj.setHeight(20);
obj.setWidth(30);
try{
FileOutputStream fs = new FileOutputStream("foo.txt");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(obj);
os.close();
}
catch(IOException ex){
}
//We set them to null so we can't access the objects on heap.
obj = null;
//Now we read them back from file
try{
ObjectInputStream is = new ObjectInputStream(new FileInputStream("foo.txt"));
check stored = (check) is.readObject();
//Check to see if it worked.
System.out.println("Variable, stored contains.." + stored.getType());
}
catch(IOException ex){
}
}
}
但它会产生以下错误。
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
at check.Check.main(Check.java:33)
任何人有任何想法来解决这个问题?