Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中读取和使用文件_Java_File_Jframe_Jlabel_Event Listener - Fatal编程技术网

在java中读取和使用文件

在java中读取和使用文件,java,file,jframe,jlabel,event-listener,Java,File,Jframe,Jlabel,Event Listener,我最近创建了一个类,它将输出到一个.txt文件。 我现在想在一个“不同的类”上阅读代码(这是一个注册程序/登录) 例如,一个用户注册后,当他丢失信息时,他可以使用JButton并输入他注册后设置的scode来找回信息。。 但我知道如何让学生阅读这些文件,但我不知道如何使用它们 以下是输出的代码: package malkawi.login; import java.awt.BorderLayout; import java.awt.ComponentOrientation; import j

我最近创建了一个类,它将输出到一个.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();
    }
    }

谢谢大家!

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

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

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

fileReader.close()
Scanner fileReader=new Scanner(new File());
while(fileReader.hasNextLine()){
String line=fileReader.readLine();
}
fileReader.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;

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

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

教程:


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

单面注释,密码最好保存为字符数组而不是字符串。
您可以在这篇文章中进一步阅读:

您不能将这大量的代码简化为基本内容吗?你的问题是“我如何读取文本文件?”还是“我如何使用我从文本文件读取的数据?”在后一种情况下,恐怕你是必须发出指令的人!我很确定我知道你在说什么,但不清楚有谁能帮助你。Op说:“我知道如何让全班同学阅读这些文件,但我不知道如何使用它们……”所以这或多或少是无用的。黑暗之眼,所以在你给出代码(将文件改为阅读后)后,我可以去。。对于(line lines:getLines()(是否已经为get lines设置了getter?{然后如果(lines.contain(“secret code”){操作…?最好在此处提供链接的关键点,以防止断开链接造成的数据丢失。
String password = data.get("password");
// 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);
// 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);