嘿伙计们,我正在做一个与此不同的小程序,但现在我正在工作。如果你运行这个程序,你可以登录或创建一个帐户,如果你没有,它将是保存在文本文件中。我的问题是我不知道获取这些变量的最佳方法是什么(“用户名”,“密码”)。现在我正在使用它: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 ();
}
}
答案 0 :(得分:2)
您可以修改代码。在文件中写入时,您可以使用"#"来分隔数据。当你再次获取时,你可以拆分并检查相同的内容。你应该忽略start,因为user-name可以是john和johnyDepp,根据你的逻辑,它们都是相同的。同时在文件中将admin值返回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();
}
}
}
}