import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class Main
{
static ObjectOutputStream outputStream;
static ObjectInputStream inputStream;
public static void main(String[] args) throws Exception
{
File file = new File("Test.ser");
outputStream = openWriteFile(file);
write(new Integer(5));
write(new Integer(3));
write(new Integer(1));
FileInputStream fileInputStream = new FileInputStream(file);
inputStream = openReadFile(fileInputStream);
readFile();
}
public static ObjectOutputStream openWriteFile(File file)
{
try
{
if (file.exists())
return new AppendableObjectOutputStream(new FileOutputStream(file, true));
return new ObjectOutputStream(new FileOutputStream(file));
}
catch (IOException e)
{
return null;
}
}
public static void write(Integer i)
{
try
{
outputStream.write(i);
}
catch (IOException ioException)
{
System.err.println("error");
}
}
public static ObjectInputStream openReadFile(FileInputStream fileInputStream)
{
try
{
if(fileInputStream.getChannel().position() != 0)
return new ObjectInputStream(fileInputStream);
return new AppendableObjectInputStream(fileInputStream);
}
catch (IOException ioException)
{
return null;
}
}
public static void readFile()
{
try
{
while (true)
{
System.out.println("here");
Integer integer = (Integer) inputStream.readObject();
System.out.println("after");
System.out.println(integer);
}
}
catch (ClassNotFoundException classNotFoundException)
{
classNotFoundException.printStackTrace();
}
catch (IOException e)
{
System.err.println("ioexecption");
e.printStackTrace();
}
}
private static class AppendableObjectOutputStream extends ObjectOutputStream
{
public AppendableObjectOutputStream(OutputStream out) throws IOException
{
super(out);
}
@Override
protected void writeStreamHeader() throws IOException
{
// do not write a header
}
}
private static class AppendableObjectInputStream extends ObjectInputStream
{
public AppendableObjectInputStream(InputStream in) throws IOException
{
super(in);
}
@Override
protected void readStreamHeader() throws IOException
{
// do not read a header
}
}
}
輸出:故障閱讀和追加到的ObjectInputStream/ObjectOutputStream的
here
ioexecption
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Main.readFile(Main.java:79)
at Main.main(Main.java:25)
我遇到了一些麻煩,從我寫信給.ser文件讀取回來。我已經運行該程序幾次,並使用getClass()
,發現這兩個流都是Appendable
版本的流。 「此處」消息打印到控制檯,但不是「之後」。 「Test.ser」出現在與classpath
相同的目錄中,幷包含內容「¬í」。
修改您的代碼,以便您可以查看堆棧跟蹤以及在println(「here」)之後在該行上引發的異常的詳細信息,然後將該(堆棧跟蹤)添加到您的問題中。 – chairbender