📄 agentdaofromfile.java
字号:
package com.tarena.abs.dao;
import java.io.*;
import java.util.HashSet;
import com.tarena.abs.model.Agent;
public class AgentDAOFromFile implements AgentDAO{
private File file;
private InputStream in;
private OutputStream out;
public AgentDAOFromFile(File file){
this.file=file;
}
public boolean addAgent(Agent user) {
HashSet hs=null;
InputStream in=null;
ObjectInputStream ois=null;
OutputStream out=null;
ObjectOutputStream oos=null;
boolean success=false;
try {
in=new FileInputStream(file);
ois=new ObjectInputStream(in);
hs=(HashSet)ois.readObject();
if(hs!=null){
success=hs.add(user);
}else{
hs=new HashSet();
success=hs.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ois!=null)try{ois.close();}catch(IOException e){}
if(in!=null)try{in.close();}catch(IOException e){}
}
try {
out=new FileOutputStream(file);
oos=new ObjectOutputStream(out);
oos.writeObject(hs);
oos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(oos!=null)try{oos.close();}catch(IOException e){}
if(out!=null)try{out.close();}catch(IOException e){}
}
return success;
}
public Agent getAgent(String name, String passwd) {
FileInputStream fis=null;
ObjectInputStream ois=null;
HashSet hs=new HashSet();
try {
fis=new FileInputStream(file);
ois=new ObjectInputStream(fis);
hs=(HashSet)ois.readObject();
for(Object obj:hs){
Agent user=(Agent)obj;
if(user.getName().equals(name)&& user.getPasswd().equals(passwd)){
return user;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ois!=null)try{ois.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}
return null;
}
public static void main(String[] args)throws Exception{
AgentDAOFromFile dao=new AgentDAOFromFile(new File("e:\\airline\\agent.txt"));
dao.addAgent(new Agent("tony","1234","tangliang@tarena.com.cn"));
System.out.println("已经写入数据!");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -