有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中读取和使用文件

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

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();
    }
    }

谢谢大家!


共 (4) 个答案

  1. # 2 楼答案

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

    Scanner fileReader = new Scanner(new File(<File to read>));
    
    while (fileReader.hasNextLine()) {
        String line = fileReader.readLine();
        <Process Line>
    }
    
    fileReader.close()
    

    如果你质疑它的自我,那么你想要的东西就模棱两可了,这里的一切都是从阅读到检查数据是否包含在内,我不能给你一个预定义的方法来使用你自己的代码,因为它是你的代码

    这确实是获取和处理数据的基础,如果发现数据很快离开循环,您可能希望调用中断

  2. # 3 楼答案

    我想你需要的是如何将地图存储到文件中,对吗?为此,你有很多选择。其中一些:

    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)使用属性对象:

    教程: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)使用自己的格式:你必须首先设计自己的格式,并实现正确的编写器/读取器(在这种情况下要求太高)

  3. # 4 楼答案

    由于您希望从其他类读取文件并使用读取的数据,因此可以尝试此方法

     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");