1

I am trying to do some kind of serialization where I can directly read and write objects from file.

To start of I just tried to write a character to file and tried to read it. This keeps giving me EOF exception always.

I am trying it on a Android device. Here is my code:

public class TestAppActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
        WriteToFile();
        Load();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public void Load () throws IOException
{
    InputStream fis;
    ObjectInputStream in = null;
    try {
        fis = new FileInputStream(Environment.getExternalStorageDirectory() + "\\test2.ser");
        in = new ObjectInputStream(fis);
        char temp = in.readChar();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        in.close();
    } 
}

public static void WriteToFile() throws Exception {
    try {
        OutputStream file = new FileOutputStream(Environment.getExternalStorageDirectory() + "\\test2.ser");
        ObjectOutput output = new ObjectOutputStream(file);
        try {
            output.writeChar('c');
        } finally {
            output.close();
        }
    } catch (IOException ex) {
            throw ex;
    }catch (Exception ex) {
        throw ex;
}
}
 }
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Vinod
  • 31,933
  • 35
  • 96
  • 119

2 Answers2

1

In this case, EOFException means there is no more data to be read, which (again in this case) can only mean that the file is empty.

Why are you using ObjectInput/OutputStreams but only writing chars? You'd be better off with DataInput/OutputStreams for that usage.

Also there is no point in catching exceptions only to rethrow them.

Also there is no point in reading a char from a file unless you are going to put it somewhere other than in a local variable that isn't even returned by the method.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

I have imported this code in my sample project with following change.

i replaced "\\test2.ser"with "/test2.ser" and it worked. please try this.

Dinesh Prajapati
  • 9,274
  • 5
  • 30
  • 47