我怎样才能像这样从文本文件中获取数据

How can i get data from Text File like this

嘿伙计们,我正在做一个小程序,它会像这样不同,但现在我正在工作 this.If 你 运行 这个程序你可以登录或创建一个帐户,如果你不没有,它将保存在文本中 file.My 问题是我不知道获取这些变量的最佳方法是什么("username","password")。现在我'我正在使用它:if(lines.startsWith(name) && lines.endsWith(pass)) 但它对我不利,因为我想获取也保存在文本文件中的布尔管理变量。所以问题是我如何从文本文件中获取这些变量(用户名、密码、管理员)?

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main{

public JTextField text;
public JTextField textt;
public JButton button;
public JButton buttons;
public JFrame frame;
final JFileChooser fc = new JFileChooser();
final JMenuBar menuBar = new JMenuBar();
public Boolean loggedin = false;
public Boolean admin = false;
public Main(){

    GUISETUP();
    MenuCreates();
    CheckLogin();
}


public void GUISETUP(){

    frame = new JFrame("MyFileCreator");
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

    JPanel p = new JPanel();
    p.setLayout(null);

    text = new JTextField();
    text.setSize(300,50);
    text.setLocation(0, 100);

    textt = new JTextField();
    textt.setSize(300,50);
    textt.setLocation(0, 50);

    button = new JButton("Create Account");
    button.setSize(300, 50);
    button.setLocation(0, 150);

    buttons = new JButton("Login");
    buttons.setSize(300, 50);
    buttons.setLocation(0, 200);



    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            writetofile();
        }
    });

    buttons.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            LogIn();
            CheckLogin();
        }
    });


    p.add(button);
    p.add(text);
    p.add(textt);
    p.add(buttons);

    frame.setContentPane(p);
    frame.setResizable(false);
    frame.setSize(600, 400);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public void CheckLogin(){

    if(loggedin.equals(true)){
        menuBar.setVisible(true);
        button.setVisible(false);
        buttons.setVisible(false);
        text.setVisible(false);
        textt.setVisible(false);
    }else{
        menuBar.setVisible(false);
    }

}


public void MenuCreates(){

    final JMenu fileMenu = new JMenu("File");

    menuBar.add(fileMenu);


    JMenuItem newAction = new JMenuItem("New");
    JMenuItem openAction = new JMenuItem("Open");

    fileMenu.add(newAction);
    fileMenu.add(openAction);


    frame.setJMenuBar(menuBar);


    newAction.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            FileCretor();
        }
    });

    openAction.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            fc.setCurrentDirectory(new java.io.File("C:\Users\bazsi\Desktop"));
            fc.setDialogTitle("Choose your File");
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            if (fc.showOpenDialog(buttons) == JFileChooser.APPROVE_OPTION){
                //System.out.println(fc.getSelectedFile().getAbsolutePath());
                try {
                    Desktop.getDesktop().open(fc.getSelectedFile());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }else{
                JOptionPane.showMessageDialog(frame,"You didnt choosed any file!","Information",JOptionPane.WARNING_MESSAGE);
            }

        }
    });
}


public void FileCretor(){

    ImageIcon icon = new ImageIcon("info.jpg");

    String answer = JOptionPane.showInputDialog(null,"Choose your File name!");
    File f = new File(answer + ".txt");
    boolean bool = false;
    if( f.exists()){
        JOptionPane.showMessageDialog(frame,"Error " + answer + " .txt  \nAlready Existing!","Insane Error",JOptionPane.ERROR_MESSAGE);
    }else if(answer.equals("")){
        JOptionPane.showMessageDialog(frame,"Error" + "\n Type in the file name!","Insane Error",JOptionPane.ERROR_MESSAGE);
    }else{

        try{
        bool = f.createNewFile();
        JOptionPane.showMessageDialog(frame,answer + ".txt" + "\nSuccesfully created!","Information",JOptionPane.INFORMATION_MESSAGE,icon);
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}

public void LogIn(){

    String name;
    String pass;

    try {

        String lines;

        FileReader fr = new FileReader("Accounts.txt");
        BufferedReader br = new BufferedReader(fr);

        name = textt.getText();
        pass = text.getText();

        while((lines = br.readLine()) != null){
            if(lines.startsWith(name) && lines.endsWith(pass)){
                loggedin = true;
            }else{
                JOptionPane.showMessageDialog(frame,"Error" + "\n Wrong Username or Password!","Insane Error",JOptionPane.ERROR_MESSAGE);
            }
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

public void ReadFromFile(){

}

public void writetofile(){

    try{

        String lines;

        FileReader fr = new FileReader("Accounts.txt");
        BufferedReader br = new BufferedReader(fr);
        FileWriter out = new FileWriter("Accounts.txt",true);
        BufferedWriter bf = new BufferedWriter(out);

        String username = textt.getText();
        String password = text.getText();

        while((lines = br.readLine()) != null){
            if(lines.startsWith(username)){
                JOptionPane.showMessageDialog(frame,"Error" + "\n This Account is Already Existing!","Insane Error",JOptionPane.ERROR_MESSAGE);
            }else{
                bf.write(username + " # " + " " + admin  +" " + password);
                bf.newLine();
            }
        }

        textt.setText("");
        text.setText("");

        bf.close();

    }catch(IOException ex){
        JOptionPane.showMessageDialog(frame, "Error While Try to Write int the File");
    }

}

public void readfromfile(){

}

public static void main (String [] args){
    Main m = new Main ();
}

}

您可以修改您的代码。在写入文件时,您可以使用“#”分隔数据,当您再次获取时,您可以拆分并检查相同的数据。您应该忽略开头,因为用户名可以是 john 和 johnyDepp,根据您的逻辑,它们都是相同的。另外 return 文件中的管理值为 true 或 false。

当你写入文件时。

bf.write(username + "#" + admin + "#" + password);

当您从文件中读取时。

      while ((lines = br.readLine()) != null) {
                    String split[] = lines.split("#");
                    String userName = split[0];
                    Boolean admin = null;
                    if (split[1].trim().length() != 0) {
                        try {
                            admin = Boolean.parseBoolean(split[1]);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                    String password = split[2];

                    if(userName.equals(userN) && password.equals(passW)){
                        if(admin != null && admin){
                            System.out.println("He is a Admin");
                        }else{
                            System.out.println("Normal Guy"); 
                        }
                    }
                }

修改: 如果您的用户不多,您可以添加相同的记录,但将添加一个额外的字段时间戳以确保更新了哪条记录。在这里我没有检查大多数更新的时间戳,因为我假设文件中的最低记录将被更新。

private static String SEPARATOR = "#";

    // Add Null pointer check
    private static void readFromFile(String username, String password) {
        BufferedReader bufferedReader = null;
        String finalCred = null;
        try {
            String line = null;
            bufferedReader = new BufferedReader(new FileReader(FILE_NAME));
            username = username.trim();
            password = password.trim();
            while ((line = bufferedReader.readLine()) != null) {
                String split[] = line.split(SEPARATOR);
                if (username.equals(split[0]) && password.equals(split[1])) {
                    finalCred = line;
                }
            }
            String split[] = finalCred.split(SEPARATOR);
            if (username.equals(split[0]) && password.equals(split[1])) {
                Boolean admin = Boolean.parseBoolean(split[2]);
                if (admin) {
                    System.out.println("User is admin");
                } else {
                    System.out.println("Not admin");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void writeInFile(String username, String password, Boolean admin) {
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(FILE_NAME,true));
            admin = (admin == null ? false : true);
            username = username.trim();
            password = password.trim();
            bufferedWriter.write(username + SEPARATOR + password + SEPARATOR + admin + SEPARATOR + Calendar.getInstance().getTimeInMillis()+"\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }