1

我正在尝试进行某种序列化,我可以直接从文件中读取和写入对象。

首先,我只是尝试将一个字符写入文件并尝试读取它。这总是给我EOF例外。

我正在 Android 设备上试用它。这是我的代码:

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;
}
}
 }
4

2 回答 2

1

在这种情况下,EOFException 意味着没有更多的数据要读取,这(同样在这种情况下)只能意味着文件是空的。

你为什么使用ObjectInput/OutputStreams但只写字符?DataInput/OutputStreams对于这种用法,您会更好。

此外,捕获异常只是为了重新抛出它们是没有意义的。

此外,从文件中读取 char 也没有任何意义,除非您将它放在某个地方,而不是放在该方法甚至不返回的局部变量中。

于 2011-11-15T09:03:06.253 回答
-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.

于 2011-11-15T09:08:24.390 回答