java在读取和追加ObjectInputStream/ObjectOutputStream时遇到问题
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)
我读报纸时有点困难。我写的那个文件。我已经运行了几次程序,使用了getClass()
,发现两个流都是Appendable
版本的流。消息“here”打印到控制台,但不是“after”。“Test.ser”与classpath
出现在同一个目录中,并包含内容“&”
# 1 楼答案
在处理输入和输出时,你应该注意对称性:如果你一边写一个字节,另一边读一个字节。如果你在一边写一个对象,你在另一边读一个对象
代码写入3个字节,并尝试读取对象。那不行
我也不明白你想用你的可附加流实现什么