【发布时间】:2023-03-12 16:15:01
【问题描述】:
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
}
}
}
输出:
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 版本的流。消息“here”打印到控制台,而不是“after”。 “Test.ser”与classpath 出现在同一目录中,并包含内容“¬í”。
【问题讨论】:
-
修改您的代码,以便您可以看到堆栈跟踪以及在 println("here") 之后的行上抛出的异常的详细信息,然后将其(堆栈跟踪)添加到您的问题中。
标签: java file serialization