我剛剛在Java中創建了我的第一個基於I/O的東西。 我想檢查寫入文件的內容是否正確保存或不保存。 爲此我寫了下面的代碼..java FileInputStream和FileOutputStream的錯誤
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)
任何人有任何想法來解決這個問題?
不要在編譯錯誤時嘗試運行代碼。打開Eclipse的「Problems」視圖,並在嘗試運行代碼之前修複列出的所有編譯錯誤。你正在做的就像試圖駕駛一輛沒有車輪的汽車。 –