0

我有一个属性文件,其中包含我在 java 程序中使用的用户名和密码,但是我无法像在数据库中那样存储多个用户名和密码,只需选择用户名和密码与数据库中的多行匹配的位置. 我想我需要在保存用户名和相应密码的文件中存储一个二维数组,但我无法弄清楚如何去做,谷歌也没有给我一种在文件中保存二维数组的方法然而。这是文件中我的用户名和密码的键/值对

    `password=k
     username=k`

这是读取它们并与用户插入的内容进行比较的代码

   `String usr = userfield.getText();
    String pwd = new String(pwdfield.getPassword());
    Properties config = new Properties();
    InputStream is;

    try {

        is = new FileInputStream("config.properties");
        config.load(is);

        if (usr.toString().equals(config.getProperty("user").toString()) && pwd.toString().equals(config.getProperty("pass").toString())) {
            new DocMenu();
            lgFrame.dispose();

        } else {
            JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);

        }

        is.close();

    } catch (Exception ex) {
        System.out.println(ex);
        ex.printStackTrace();
    }`

有人可以告诉我如何更改属性文件和代码,以便我能够在文件中拥有多个用户名和密码,以授予任何用户访问权限,只要他们的用户名和密码存在。

4

4 回答 4

1

如果您将属性名称存储为某个键与用户名的串联,密码存储为这样的值;

#Some bad passwords
username.bob=password
username.scott=tiger
username.admin=admin

..那么你可以这样检查;

String password = config.getProperty("username." + usr.toString());
if (password != null && password.equals(pwd.toString())) {
  new DocMenu();
  lgFrame.dispose();
} else {
  JOptionPane.showMessageDialog(lgFrame, "Wrong credentials try again", "Oops", JOptionPane.ERROR_MESSAGE);
}
于 2012-10-16T12:47:09.970 回答
1

在您发布的代码中,您在属性中有“用户名”,并且您正在尝试读取“用户”属性。密码也是如此。

但这只会让你有一对用户/密码。您的属性文件中应该有一个更详细的结构。例如你可以有

user1=pwd1
user2=pwd2
...

然后检查类似:

if (password != null && password.equals(config.getProperty(usr)){
 // ok ...
}
于 2012-10-16T12:52:02.000 回答
0

如果你必须使用属性,我认为除了做之外别无选择

username.1
username.2
username.3

并迭代直到你有一个你找不到属性的索引(在这种情况下,username.4)。

对于更复杂的配置,我会研究诸如Apache Commons Config之类的框架,它可以处理元素列表

于 2012-10-16T12:48:31.037 回答
0

正如所承诺的,这里是 HashSet 序列化/反序列化代码:

import java.util.*;
import java.io.*;

class UserPasswordMap{
   private HashMap<String,String> userMap;
   private String m_filename;
   public UserPasswordMap()
   {
       userMap = null;
       m_filename = null;
       userMap = new HashMap<String,String>();
   }

   public UserPasswordMap(String filename, String credo)
   {
       try{
          m_filename = filename;
          File f = new File(m_filename);
          userMap = new HashMap<String,String>();
          if(f.exists() && (!(f.canRead() && f.canWrite()))){ 
              System.err.println("Oops, Insufficient permissions to read/write for filename: "+m_filename);
          }else{
              f.createNewFile();
          }
       }catch(Exception e){
           System.err.println(e.getMessage());
       }

       if(credo.equals("D")){
           try{
           ReadMap(filename);
           }catch(Exception e){ System.err.println(e.getMessage());}
       }
   }
   public void ReadMap(String filename) throws IOException, ClassNotFoundException
   {
       FileInputStream fis = new FileInputStream(filename);
       ObjectInputStream ois = new ObjectInputStream(fis);
       userMap = (HashMap<String,String>)ois.readObject();
       fis.close();
   }

   public void WriteMap(String filename) throws IOException{
       FileOutputStream fos = new FileOutputStream(filename);
       ObjectOutputStream oos = new ObjectOutputStream(fos);
       oos.writeObject(userMap);
       oos.close();
   }

   public ArrayList<String> getUsers()
   {
       ArrayList<String> users = new ArrayList<String>();
       if(userMap == null){
           return null;/*or return users*/
       }else{
           for(String s:userMap.keySet()){
               users.add(s);
           }
       }
       return users;
   }

   public ArrayList<String> getPasswords()
   {
       ArrayList<String> passwords = new ArrayList<String>();
       if(userMap == null){
           return null;/*or return users*/
       }else{
           for(String s:userMap.values()){
               passwords.add(s);
           }
       }
       return passwords;
   }

   public String getPassword(String username)
   {
       return userMap.get(username);
   }

   public void addUser(String username, String password){
       userMap.put(username, password);
       try{
           WriteMap(m_filename);
       }catch(Exception e){
           System.err.println(e.getMessage());
       }
   }

   public void saveData(){
       if(m_filename == null){
           System.err.println("File-Name is not supplied");
       }else{
           try{
              WriteMap(m_filename);
           }catch(Exception e){
               System.err.println(e.getMessage());
           }
       }
   }
}

和测试代码:

public class Main{
    private UserPasswordMap map;
    public static void main(String[] args){
       Main obj = new Main();
       obj.init();
       Scanner scan = new Scanner(System.in);
       System.out.println("0. Init With Serialisation(CAN THROW ERROR)");
       while(true){
          System.out.println("1. Add New User");
          System.out.println("2. Query Permissions");
          System.out.println("3. Exit");
          int data = scan.nextInt();
          switch(data){
          case 0: obj.initWithSerialisation();
          break;
          case 1: obj.addNewUser();
          break;
          case 2: obj.queryPerms();
          break;
          case 3: System.exit(0);
          }
       }
    }

    public void init()
    {
         map = new UserPasswordMap("try1.ser","");
    }

    public void initWithSerialisation()
    {
        map = new UserPasswordMap("try1.ser","D");
    }
    private Scanner scan;
    public void addNewUser()
    {
        System.out.print("Enter User:");
        scan = new Scanner(System.in);
        String username = scan.nextLine();
        System.out.print("Enter Pass:");
        String password = scan.nextLine();
        map.addUser(username, password);
    }

    public void queryPerms()
    {
        System.out.print("Enter User:");
        if(scan == null){ scan = new Scanner(System.in);}
        String username = scan.nextLine();
        System.out.print("Enter Pass:");
        String pass = scan.nextLine();

        if(map.getUsers().contains(username) && map.getPassword(username).equals(pass)){
            System.out.println("authenticated!");
        }else{
            System.out.println("Oops Wrong credentials!");
        }
    }
}
于 2012-10-16T13:42:44.103 回答