开发者

assistance with first Serialization program

开发者 https://www.devze.com 2023-01-07 15:01 出处:网络
Here\'s the code I\'m using: public class Ser implements Serializable { int x,y; String name; public Ser(int a, int b, String c) {

Here's the code I'm using:

public class Ser implements Serializable {
int x,y;
String name;
public Ser(int a, int b, String c) {
    x=a;
    y=b;
    name = c;
  }
}

import jav开发者_高级运维a.io.*;

public class testSer {
public static void main(String[] args) {
    FileOutputStream testStream = new FileOutputStream("serText.ser");
    ObjectOutputStream testOS = new ObjectOutputStream(testStream);
    Ser objTest = new Ser(1,2, "Nikhil");
    testOS.writeObject(objTest);
    testOS.close();
  }
}

Here are the errors I'm receiving:

assistance with first Serialization program

I've created the *.ser file manually in the folder(although the book says compiler automatically creates one) but the problem still persists.

RELP!


You need to somehow deal with IOException, either catching it or throwing from main. For a simple program, throwing is probably fine:

public static void main(String[] args) throws IOException


You're not dealing with IOException. You need to either catch it or throw it explicitly.

try{
  // Your code
}catch(IOException e){
  // Deal with IOException
}

or

public static void main(String[] args) throws IOException{
  // Your code
}

This is all a consequence of Java having checked exceptions, of which IOException is one.

For your purposes, the second is probably fine since an IO failure can't really be recovered from. In larger programs, you'll almost certainly want to recover from transient IO failures and thus the first would be more appropriate.


You need to use a try/catch block, handling exceptions that are declared as thrown in the methods you are using. It would be worthwhile to read up on exception handling.

0

精彩评论

暂无评论...
验证码 换一张
取 消