以下是我序列化和反序列化通用堆栈
反序列化方法的程序片段
public Stack<?> readAll(Path aPath){
Stack<?> temp = new Stack<>();
try(ObjectInputStream readStream = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(aPath)))) {
temp = (Stack<?>) readStream.readObject();
}catch(EOFException e) {
e.printStackTrace();
System.out.println("EOF");
}catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
return temp;
}
序列化方法
public void writeAll(Path aPath) {
try(ObjectOutputStream writeStream = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(aPath)))) {
writeStream.writeObject(this);
}catch(IOException e) {
e.printStackTrace();
}
}
数据如何序列化和反序列化
import java.nio.file.*;
public class StackTrial {
public static void main(String[] args) {
String[] names = {"A","B","C","D","E"};
Stack<String> stringStack = new Stack<>(); //Stack that will be Serialized
Stack<String> readStack = new Stack<>(); //Stack in which data will be read
Path aPath = Paths.get("C:/Documents and Settings/USER/Beginning Java 7/Stack.txt");//Path of file
for(String name : names) { //pushing data in
stringStack.push(name);
}
for(String a : stringStack) { //displaying content
System.out.println(a);
}
stringStack.writeAll(aPath); //Serialize
readStack = (Stack<String>) readStack.readAll(aPath);//Deserialize
for(String a : readStack) { //Display the data read
System.out.println(a);
}
}
}
问题: readAll() 方法的返回类型是否真的在做任何事情来提供灵活性,或者如果我将其更改为这无关紧要Stack<T>
我的逻辑是,在读取文件时可能有可能写入文件的数据可能是Stack<Integer>
这样的回来可能会引起麻烦