0
以下是我的程序序列化和反序列化一般堆棧
反序列化方法的片段Java的通用串行化,可迭代堆棧
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>
也許因此而回讀它可能會造成麻煩
這裏:'公衆堆棧 readAll(Path aPath){...}'''下面公共沒有必要嗎? –
是的。否則該方法將不是一個通用的方法,編譯器會搜索一個名爲T的具體類。 –
以及我的方法'public stack > readAll(Path aPath)''我不需要''因爲它是一個通配的權利?只有當它是'公共堆棧 readAll(Path aPath)''我需要一個'' –