网页聊天service
2015-12-19 18:16
176 查看
package pers.zkr.chat.service; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.LinkedList; import java.util.Properties; public class ChatService { //使用单例模式来设计ChatService private static ChatService cs; //使用Properties对象保存系统的所有用户 private Properties userList; //使用LinkedList对象保存聊天信息 private LinkedList<String> chatMsg; //机器私有 private ChatService(){ } public static ChatService instance(){ if(cs==null){ cs= new ChatService(); } return cs; } public boolean validLogin(String user,String pass) throws IOException{ String loadPass = loadUser().getProperty(user); //登录成功! if(loadPass != null && loadPass.equals(pass)){ return true; } return true; } //新注册用户 public boolean addUser(String name , String pass) throws Exception{ if(userList == null){ userList = loadUser(); } if(userList.containsKey(name)){ throw new Exception("用户名已经存在,请重新选择用户名"); } userList.setProperty(name , pass); saveUserList(); return true; } // 获取系统中所有聊天信息 public String getMsg(){ //如果chatMsg对象为null,表明不曾开始聊天 if(chatMsg == null){ chatMsg=new LinkedList<String>(); return ""; } StringBuilder result = new StringBuilder(); //将chatMsg中所有聊天信息拼接起来 for(String line : chatMsg){ result.append(line + "\n"); } return result.toString(); } //用户发言,添加聊天信息 public void addMsg(String user , String msg){ if(chatMsg == null){ chatMsg = new LinkedList<String>(); } //最多保存40条聊天信息,当超过40条之后,将前面聊天信息删除 if(chatMsg.size() > 40){ chatMsg.removeFirst(); } //添加新的聊天信息 chatMsg.add(user + "说:" + msg); } //************************下面是私有的系统的工具类 private boolean saveUserList() throws IOException { // TODO Auto-generated method stub if(userList == null){ return false; } userList.store(new FileOutputStream("userFile.properties"), "User info list"); return true; } private Properties loadUser() throws IOException { // TODO Auto-generated method stub if(userList == null){ //加载userFile.properties文件 File f=new File("userFile.properties"); if(!f.exists()){ f.createNewFile();//不存在新建 } String path= f.getAbsolutePath(); System.out.println(path); userList =new Properties(); userList.load(new FileInputStream(f)); } return userList; } }
相关文章推荐
- ARM使用术语清除(flush)和清理(clean)表示对cache的两种基本操作
- DDL触发器的应用
- JavaScript 浏览器检测
- Storm环境配置
- Apple的示例SpeakHere不能运行解决
- mysql主从复制
- 造轮子_Windows服务操作之sc和net命令
- 1.linux运维系列写在最开始
- [Java代码] java使用itext按页码拆分pdf文件
- Maven依赖包查询地址
- hdu 2899 hdu 3400 三分/几何
- Delphi数据类型
- 高性能事务处理配置
- 几篇关于Linux文件系统的文章
- 第16周项目1(1)直接插入排序
- tools.percona.com dba 服务
- Base64编码及其运用
- jquery mobile 移动web(6)
- 麦兜个人博客开通啦!!!
- [Java学习] Java文件处理类