import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
new Main().runFunction();
}
private void writeIn(File file, LinkedList<String> list) throws IOException {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(file, false));
out.writeObject(list);
} finally {
if (out != null) {
out.close();
}
}
}
private void readOut(File file) throws IOException, ClassNotFoundException {
ObjectInputStream objectIn = null;
try {
objectIn = new ObjectInputStream(new FileInputStream(file));
Object data;
while ((data = objectIn.readObject()) != null) {
List<String> list = (List)data;
for (String poi : list) {
System.out.println(poi);
}
}
}finally {
if (objectIn != null) {
objectIn.close();
}
}
}
private void runFunction() {
File file = new File("d:\\java\\test\\ObjectFile.txt");
LinkedList<String> list = new LinkedList<String>();
String[] string = {"stringa\n", "stringb\n", "stringc\n", "stringd\n"};
for (String temp : string) {
list.add(temp);
}
try {
if (file.exists() == false) {
if (file.getParentFile().exists() == false)
file.getParentFile().mkdirs();
file.createNewFile();
}
writeIn(file, list);
readOut(file);
} catch (IOException e) {
e.getStackTrace();
throw new RuntimeException("\n程序运行发生错误,请重试");
}catch(ClassNotFoundException ee) {
ee.getStackTrace();
throw new RuntimeException("\n类运行发生错误,请重试");
}
}
}
0