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
인 것으로 나타났습니다. "here"메시지는 "after"가 아닌 콘솔에 인쇄됩니다. "Test.ser"는 classpath
과 같은 디렉토리에 나타나며 내용 "íí"을 포함합니다.
stacktrace와 println ("here") 다음에 나오는 예외에 대한 세부 정보를 볼 수 있도록 코드를 수정 한 다음 질문에 stacktrace를 추가하십시오. – chairbender