2016-10-05 16 views
1

ちょっと私はこのように少し異なるプログラムをやっていますが、今私はthis.Ifを動作させていますあなたがログインするか、あなたは持っていないし、テキストファイルに保存されます。私の問題は、これらの変数( "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(); 
} 

} 
+0

ファイルに書き込むたびにtrim()メソッドを使用します。私はあなたがそれが有用であるとわかったら、正しい印をつけてください。 – cody123

答えて

2

コードを変更することができます。ファイルに書いている間、あなたは "#"を使ってデータを分けることができます。また、あなたが再びフェッチするときに、それを分割してチェックすることができます。 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(); 
       } 
      } 
     } 
    } 
+0

もう一つの問題があります。すべてのアカウントはちょうど普通の人です...私は管理者を作ることができます... –

+0

もう少し説明できますか?あなたは、あなたが普通の男か普通の人を管理者にしたいと言っているのですか? – cody123

+0

@BalázsSzmetana私は自分の答えを変更しましたが、ボトルネックになるので、より多くのデータが必要であるという制限があります。あなたは、トラフィックを持っていないときにいくつかのクリーンアップ活動を行う必要があります。私があなたの問題を解決した場合、正しいとupvoteをマークしてください。 – cody123

関連する問題