简体   繁体   English

Java中使用Swing进行文件处理编程

[英]File handling programming with Swing in java

I need help with step 2 to understand the working of File handling in java,,,,... 我需要第2步的帮助,以了解Java,...,文件处理的工作原理

This is what i am doing.... :- problem: Exception Note: i am a newbie with this concept to please tell me what is wrong in my code. 这就是我正在做的....:-问题:异常注:我是这个概念的新手,请告诉我代码中的错误。

-Create a mini Java application using swing, which must ask for a Username and Password and have a create button. -使用swing创建一个迷你Java应用程序,该应用程序必须询问用户名和密码并具有创建按钮。

-as soon as the create button is pressed a new directory must be created with the name of the user and password must be saved as password.txt file inside that directory. -按下创建按钮后,必须立即创建一个带有用户名的新目录,并且密码必须另存为该目录内的password.txt文件。

-if the directory already exists, then a pop-up windows should appear saying "User already exists". -如果目录已经存在,则将出现一个弹出窗口,提示“用户已经存在”。

I've tried for hours now but can't do it properly, little help is much appreciated. 我已经尝试了几个小时,但无法正确完成,非常感谢您的帮助。

I need to see some code for this, while i am continuously trying to fix mine. 在我不断尝试修复我的问题时,我需要查看一些代码。

Updated Code : 更新的代码:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;

class CreateUser implements ActionListener
{   
    JFrame fr;  //Frame
    JButton b1;  //Create Button
    JLabel lb1, lb2;    //Username and password
    JTextField tf1, tf2;    //Username and password input fields
    JPanel p1;

    CreateUser()
    {
        //Setting the frame
        fr=new JFrame();
        fr.setLayout(null);
        fr.setSize(400,400);

        //setting panel
        p1=new JPanel();
        p1.setBounds(0,0,400,400);
        p1.setLayout(null);

        //setting Username Label
        JLabel lb1=new JLabel("Username: ");
        lb1.setBounds(50,50,70,30);
        p1.add(lb1);

        //setting Username Text Field
        JTextField tf1 = new JTextField();
        tf1.setBounds(150,50,150,30);
        p1.add(tf1);


        //setting Password Label
        JLabel lb2=new JLabel("Password: ");
        lb2.setBounds(50,100,70,30);
        p1.add(lb2);

        //setting Password Text Field
        JTextField tf2 = new JTextField();
        tf2.setBounds(150,100,150,30);
        p1.add(tf2);

        //setting Button
        b1=new JButton("Create");
        b1.setBounds(100,200,100,40);   
        p1.add(b1);

        fr.add(p1);
        fr.setVisible(true);    
        b1.addActionListener(this);
        tf1.addActionListener(this);
        tf2.addActionListener(this);

    }

    public static void main(String s[])
    {
        new CreateUser();
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==b1)
        {   
            {
                String uid = tf1.getText();
                String pass = tf2.getText();

                String dir = System.getProperty("user.dir");

                //Creating a new folder Users

                File file = new File(dir+"\\users");
                if (!file.exists()) 
                {
                    if (file.mkdir()) 
                    {
                        System.out.println("Directory is created!");
                    } 
                    else 
                    {
                        System.out.println("Failed to create directory!");
                    }
                }
                dir = dir+"\\users";

                //Creating a folder named with username inside Users folder

                File file1 = new File(dir+"\\"+uid);
                if (!file1.exists()) 
                {
                    if (file1.mkdir()) 
                    {
                        System.out.println("Directory is created!");
                    } 
                    else 
                    {
                        System.out.println("Failed to create directory!");
                    }
                }

                //Storing Password.txt inside users/username folder

                try
                {
                    FileOutputStream fout=new FileOutputStream("password.txt");
                    byte b[]=pass.getBytes();
                    fout.write(b);
                }
                catch(Exception ee)
                {}
            }
        }
    }           
}

Many potential problems here so let's go through the code: 这里有许多潜在的问题,所以让我们来看一下代码:

class CreateUser implements ActionListener {

Minor problem: avoid having your GUI classes implement your control interfaces. 较小的问题:避免让您的GUI类实现您的控制接口。 This gives the class too much responsibility, cluttering the class, leading to unwieldy difficult to debug code. 这给了类太多的责任,使类​​混乱,导致难以调试代码。 Better to use an anonymous inner class or non-anonymous inner class. 最好使用匿名内部类或非匿名内部类。

JFrame fr; // Frame
JButton b1; // Create Button
JLabel lb1, lb2; // Username and password
JTextField tf1, tf2; // Username and password input fields
JPanel p1;

Minor problem: the fields should always be private unless you've a specific reason to make the public. 次要问题:除非您有特定的公开理由,否则这些字段应始终为私有字段。 You don't, so make them private here. 您没有,因此请在此处将其设为私有。

CreateUser() {
    // Setting the frame
    fr = new JFrame();
    fr.setLayout(null);
    fr.setSize(400, 400);

Minor problem: Never, never, never use null layouts. 次要问题:从不,从不,从不使用null布局。 While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. 尽管null布局和setBounds()似乎是Swing新手喜欢创建复杂GUI的最简单和最佳方法,但您创建的Swing GUI越多,使用它们时将遇到的困难就越大。 They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one. 当GUI调整大小时,它们不会调整组件的大小;它们是要增强或维护的皇家女巫;放置在滚动窗格中时,它们会完全失败;在所有平台或与原始分辨率不同的屏幕分辨率下查看时,它们看起来都是令人毛骨悚然的。

    // setting panel
    p1 = new JPanel();
    p1.setBounds(0, 0, 400, 400);
    p1.setLayout(null);

Same problem. 同样的问题。 Learn the layout managers, and then use the layout managers. 学习布局管理器,然后使用布局管理器。

    // setting Username Text Field
    JTextField tf1 = new JTextField();

Major problem : You're shadowing a field here. 主要问题 :您正在此处遮盖一个字段。 By re-declaring the tf1 variable within the class constructor, you're assigning a JTextField object to a local variable, which means that the tf1 field in the class remains empty/unassigned/null. 通过在类构造函数中重新声明tf1变量,可以将JTextField对象分配给局部变量,这意味着类中的tf1字段保持为空/未分配/空。 This can lead to a NullPointerException being called if you ever try to use this null field. 如果您尝试使用此null字段,则可能导致调用NullPointerException。

So if you're going to do the object creation and assignments within the constructor or an init method, then instead of 因此,如果您要在构造函数或init方法中进行对象创建和分配,则可以使用

    JTextField tf1 = new JTextField();

do: 做:

    tf1 = new JTextField(); 


    // setting Password Text Field
    JTextField tf2 = new JTextField();

Same problem. 同样的问题。 Also this should be a JPasswordField not a JTextField. 同样,这应该是JPasswordField而不是JTextField。

    // setting Button
    b1 = new JButton("Create");

For some reason you assign the button correctly. 由于某种原因,您正确分配了按钮。 Go figure. 去搞清楚。

public static void main(String s[]) {
    new CreateUser();
}

Always start a Swing application on the Swing event thread or EDT (for Event Dispatch Thread). 始终在Swing事件线程或EDT(用于事件调度线程)上启动Swing应用程序。 So do: 这样:

public static void main(String s[]) {
    SwingUtilities.invokeLater(() -> new CreateUser());        
}

try {
    FileOutputStream fout = new FileOutputStream("password.txt");
    byte b[] = pass.getBytes();
    fout.write(b);
} catch (Exception ee) {

}

Major problem: never never have an empty catch block which is the coding equivalent of trying to drive a car with a blindfold on. 主要问题:永远不会有空的挡块,这相当于试图开车蒙上眼罩的汽车。 At least print out the stacktrace so you will be notified of errors if and when they occur. 至少打印出堆栈跟踪,以便在发生错误时以及发生错误时通知您。 Also, if you're writing out text, use a writer such as a PrintWriter. 另外,如果要写文本,请使用诸如PrintWriter之类的书写器。 I won't go into the dangers of writing out password text, but obviously it's something you'd never do in real life. 我不会写出密码文本的危险,但是显然这是您在现实生活中从未做过的事情。

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

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