⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 userdaofromfile.java

📁 java编写的控制台用户注册登陆小程序.
💻 JAVA
字号:
package day08.user_management;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Iterator;

public class UserDaoFromFile implements UserDao{
	private File userFile;
	public UserDaoFromFile(File file){
		this.userFile=file;
		FileOutputStream fos=null;
		ObjectOutputStream oos=null;
		if(file.exists() && file.length()!=0){
			return;
		}
		try {
			fos=new FileOutputStream(userFile);
			oos=new ObjectOutputStream(fos);
			oos.writeObject(new HashSet());
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(oos !=null)try{oos.close();}catch(IOException e){}
			if(fos !=null)try{fos.close();}catch(IOException e){}
		}
		
	}

	public synchronized boolean addUser(User user) {
		FileInputStream fis=null;
		ObjectInputStream ois=null;
		FileOutputStream fos=null;
		ObjectOutputStream oos=null;
		HashSet set=null;
		boolean wasAdd=false;
		try {
			fis=new FileInputStream(userFile);
			ois=new ObjectInputStream(fis);
			set=(HashSet)ois.readObject();
			wasAdd=set.add(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){}
		}
		
		if(!wasAdd){
			return false;
		}
		
		try {
			fos=new FileOutputStream(userFile);
			oos=new ObjectOutputStream(fos);
			oos.writeObject(set);
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(oos !=null)try{oos.close();}catch(IOException e){}
			if(fos !=null)try{fos.close();}catch(IOException e){}
		}
		return true;
	}

	public synchronized User getUser(String name, String passwd) {
		FileInputStream fis=null;
		ObjectInputStream ois=null;
		HashSet set=null;
		try {
			fis=new FileInputStream(userFile);
			ois=new ObjectInputStream(fis);
			set=(HashSet)ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(ois !=null)try{ois.close();}catch(IOException e){}
			if(fis !=null)try{fis.close();}catch(IOException e){}
		}
		
		Iterator it=set.iterator();
		while(it.hasNext()){
			User u=(User)it.next();
			if(u.getUserName().equals(name) && u.getPassword().equals(passwd)){
				return u;
			}
		}
		return null;
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -