私たちのアプリケーションには、次のコードに還元できる問題があります。
public static void main(String[] args) throws IOException, ClassNotFoundException {
File tempFile = File.createTempFile("teststream", "");
FileOutputStream fos = new FileOutputStream(tempFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(1);
oos.writeObject("foo");
oos.writeInt(2);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream(tempFile);
ObjectInputStream ois = new ObjectInputStream(fis);
int n1 = ois.readInt();
Object o1 = ois.readObject();
int n2 = ois.readInt();
}
このコードは機能しますが、次の行にコメントを付けると:
Object o1 = ois.readObject();
次の行
int n2 = ois.readInt();
EOFException
オブジェクトと整数を書き込んだため、ファイルにデータがありますが、がスローされます。readIntのjavadoc は、この動作を示していません。これについては少し心配です。コードで実際のファイルの例外と間違ったタイプのコンテンツEOFException
を区別したいからです。
例外のスタック トレースは次のとおりです。
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2793)
at java.io.ObjectInputStream.readInt(ObjectInputStream.java:968)
これは、次のコードがDataInputStream
例外をスローすることを意味します。
public final int readInt() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
しかしin.read()
、入力ストリームにデータがある場合に負の数を返すことは想定されていないので、私は本当に興味をそそられます。
readInd
これが起こらないようにするために私のコードでできることはありますwriteObject
か?
私はこのバージョンのJavaを使用しています:
java version "1.7.0_07"
OpenJDK Runtime Environment (IcedTea7 2.3.2) (ArchLinux build 7.u7_2.3.2-2-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)