繁体   English   中英

在Java中读取和使用文件

[英]Reading and using Files in java

我最近做了一个类,将其输出到.txt文件。 我现在想在“不同的类”上阅读代码(这是一个注册程序/登录),例如,一个用户注册了,然后当他丢失信息时,他可以使用JButton将其找回并输入注册后设置的代码。.但是我知道如何使该类读取文件,但是我不知道如何使用它们,这是输出的代码:

package malkawi.login;


import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.swing.*;

import malkawi.login.JTextFieldLimit;


/**
 * 
 * @author Defiledx1
 * sign up
 */

public class SignUp extends JFrame implements EventListener {



    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JButton complete = new JButton("Next");
    JLabel fname = new JLabel("Name: ");
    JLabel Mname = new JLabel("Middle Name: ");
    JLabel Lname = new JLabel("Last Name: ");
    JLabel user = new JLabel("Username: ");
    JLabel pass = new JLabel("Password: ");
    JLabel info = new JLabel("Click Next to Continue");
    JLabel email = new JLabel("Email: ");
    JLabel scode = new JLabel("Secret Code: ");
    JTextField fname1 = new JTextField();
    JTextField Mname1 = new JTextField();
    JTextField Lname1 = new JTextField();
    JTextField user1 = new JTextField();
    JPasswordField pass1 = new JPasswordField();
    JTextField email1 = new JTextField();
    JTextField scode1 = new JTextField();
    JRadioButton showPass = new JRadioButton("Show Pass");
    boolean good;


    public SignUp() {
        super("Sign Up - Flare By Malkawi");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600, 400);
        setResizable(false);
        setVisible(true);
        JTextFieldFilter jtff = new JTextFieldFilter(JTextFieldFilter.NUMERIC);
        jtff.setNegativeAccepted(true);
        setVisible(true);
        setLayout(new GridLayout(0, 2, 10, 10));
        setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        /*
         * Limitations
         */
        fname1.setDocument(new JTextFieldLimit(10));
        Mname1.setDocument(new JTextFieldLimit(1));
        Lname1.setDocument(new JTextFieldLimit(10));
        user1.setDocument(new JTextFieldLimit(15));
        email1.setDocument(new JTextFieldLimit(80));
        //scode1.setDocument(new JTextFieldLimit(5));
        scode1.setDocument(jtff);
        /*
         * End Of Limitations
         */
        /*
         * RadioButton Checked : Unchecked
         */
        showPass.addItemListener(new ItemListener() {
             public void itemStateChanged(ItemEvent e) {          
                 showPassword(e.getStateChange() == 1 ? true : false);

             }           
          });
        /*
         * End of RadioButton Checked : UnChecked
         */
        /*
         * Action of registration
         */
          complete.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
                    abilities();
                    if(good == false) {
                        abilities();
                    } else {
                 try {
                    outPutInformation();
                } catch (FileNotFoundException | UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    System.out.println("Flare is unable at the moment!");
                }
                }
                }
            }); 
          /*
           * End of Action of registration
           */
          //  Dimension labelSize = info.getPreferredSize();
          /*
           * Start of placements
           */
            //add(info);
            add(fname);
            add(fname1);
            add(Mname);
            add(Mname1);
            add(Lname);
            add(Lname1);
            add(user);
            add(user1);
            add(pass);
            add(pass1);
            add(email);
            add(email1);
            add(scode);
            add(scode1);
            add(complete);
            add(showPass);
            add(info);
            pack();
    }

    String filename1 = user1.getText();
    String firstname1 = fname1.getText();
     String middlename1 = Mname1.getText();
     String lastname1 = Lname1.getText();
    String username1 = user1.getText();
    @SuppressWarnings("deprecation")
    String password1 = pass1.getText();
    String hotmail1 = email1.getText();
    String secretcode1 = scode1.getText();

    public void abilities() {
        if (firstname1.contains(JTextFieldFilter.ALPHA_NUMERIC)) {//tommorow defiled add more!!
            JFrame abort = new JFrame("Firstname needs to contain numbers and letters");
            JLabel label = new JLabel("Firstname needs to contain numbers and letters");
            abort.setLayout(new BorderLayout());
            abort.setDefaultCloseOperation(EXIT_ON_CLOSE);
            abort.setSize(400, 200);
            abort.setResizable(false);
            abort.add(label, BorderLayout.CENTER);
            abort.pack();
            abort.setVisible(true);
            good = false;
        } else {
            good = true;
        }
    }

    public void showPassword(boolean showP) {
        if (showP == true) {
            pass1.setEchoChar((char)0);
        } else {
            pass1.setEchoChar('*');
        }

    }

    /*
     * File Output Requirements

    String filename = user1.getText();
    String firstname = fname1.getText();
    String middlename = Mname1.getText();
    String lastname = Lname1.getText();
    String username = user1.getText();
    @SuppressWarnings("deprecation")
    String password = pass1.getText();
    String hotmail = email1.getText();
    String secretcode = scode1.getText();

     * File Output done
     */


    public void outPutInformation() throws FileNotFoundException, UnsupportedEncodingException {

        String filename = user1.getText();
        String firstname = fname1.getText();
        String middlename = Mname1.getText();
        String lastname = Lname1.getText();
        String username = user1.getText();
        @SuppressWarnings("deprecation")
        String password = pass1.getText();
        String hotmail = email1.getText();
        String secretcode = scode1.getText();

        PrintWriter writer = new PrintWriter("data/usersaves/"+filename+".txt", "UTF-8");
        writer.println("First Name: "+firstname);
        writer.println("Middle Name: "+middlename);
        writer.println("Last Name: "+lastname);
        writer.println("Username: "+username);
        writer.println("Password: "+password);
        writer.println("Email: "+hotmail);
        writer.println("Secret Code: "+secretcode);
        writer.close();
    }
    }

谢谢!

由于您想从其他类中读取文件并使用读取她的数据,因此可以尝试一下。

 Map<String,String> data = new HashMap<>();
FileReader fr = new FileReader(fileToRead);
String str = "";
while((str = fr.readLine()) != null){
   String s = str.split(": ");
   data.add(s[0],s[1]);
 }

 return data;

然后,您可以根据键从映射中提取值。 现在,您可以调用具有该代码的此类的方法,该代码将返回值映射。 现在,您可以将所有内容写为

String password = data.get("password");

一方面,密码最好保留为char数组而不是字符串。 您可以在这篇文章中进一步阅读: 为什么String不适合parsswoords

您可以尝试使用扫描仪,然后遍历所有行,扫描仪的工作原理如下:

Scanner fileReader = new Scanner(new File(<File to read>));

while (fileReader.hasNextLine()) {
    String line = fileReader.readLine();
    <Process Line>
}

fileReader.close()

您质疑从阅读到必须检查数据的地方这是我自己的模棱两可的东西,我无法为您提供一种使用您自己的代码的预定义方法,因为它是您的代码

这确实是获取和处理数据的基础,如果发现数据会迅速离开循环,则可能需要中断一下

我认为您需要的是如何将地图存储到文件中,对吗? 为此,您有很多选择。 他们中的几个:

1)使用标准对象序列化:

教程: http//www.tutorialspoint.com/java/java_serialization.htm

// prepare data
Map<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");

// save to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("config.ser")));
oos.writeObject(data);
oos.close();

// load from file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("config.ser")));
Object loadedUntyped = ois.readObject();
ois.close();

// you can check type here, etc.
Map<String, String> loadedTyped = (Map<String, String>) loadedUntyped;
System.out.println("loaded: " + loadedTyped);

2)使用Properties对象:

教程: http//tamanmohamed.blogspot.cz/2012/12/java-storeload-properties-file-in-both.html

// prepare data
Properties data = new Properties();
data.setProperty("key1", "value1");

// save data
data.store(new FileOutputStream(new File("config.properties")), "example");

// load data
Properties loaded = new Properties();
loaded.load(new FileInputStream(new File("config.properties")));
System.out.println("loaded: " + loaded);

3)使用您自己的格式:您必须首先设计自己的格式并实现正确的编写器/阅读器(这种情况要求太高)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM