62,616
社区成员
发帖
与我相关
我的任务
分享
package com.qq.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Test test = new Test();
QQ qq = new QQ(1, "231", "fds", "fds", "sadf", 3213, "fdsaf", "fdsafsd");
System.out.println("新增的QQ :" + qq + "\n");
test.saveDataToFile("qq.txt", qq);
System.out.println("保存后的数据:");
List<QQ> list = test.getDataFromFile("qq.txt");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
/**
* 写数据
*
* @param filePath
* @param newQQ
*/
public void saveDataToFile(String filePath, QQ newQQ) {
List<QQ> qqs = getDataFromFile(filePath);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
qqs.add(newQQ);
try {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
fos = new FileOutputStream(file, false);
oos = new ObjectOutputStream(fos);
for (int i = 0; i < qqs.size(); i++) {
oos.writeObject(qqs.get(i));
}
oos.writeObject(null);
oos.flush();
oos.reset();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 读数据
*
* @param filePath
* @return
*/
public List<QQ> getDataFromFile(String filePath) {
List<QQ> qqs = new ArrayList<QQ>();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
// 第一次执行时,因为没有数据,所以强行加入一个结束符号
FileOutputStream fos = new FileOutputStream(file, true);
fos = new FileOutputStream(file, true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(null);
oos.flush();
oos.close();
}
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
QQ qq = null;
while ((qq = (QQ) ois.readObject()) != null) {
qqs.add(qq);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return qqs;
}
}