简体   繁体   English

从文本文件读取到文本字段Java

[英]Read from textfile to textfield java

I have a text file which stores data about a user, from username, password and other details. 我有一个文本文件,用于存储有关用户名,密码和其他详细信息的用户数据。 In the text file, each user's data is stored in one line and separated using ",". 在文本文件中,每个用户的数据存储在一行中,并使用“,”分隔。 I am trying to read from the file and list all the usernames. 我正在尝试从文件中读取并列出所有用户名。 usernames are first one the line 用户名是第一个

In the following code, I manage to read and output, but only the last one from the text file. 在以下代码中,我设法读取和输出,但仅读取和输出文本文件中的最后一个。 How can I read and output all. 如何读取和输出所有内容。

try {
        File f = new File("/Users/Nisham/Desktop/javapwd.txt");
        Scanner sc = new Scanner(f);



        while(sc.hasNextLine()){

            String line = sc.nextLine();
            String[] details = line.split(",");
            String name = details[0];
            //int age = Integer.parseInt(details[2]);
            jTextArea1.setText(name);

        }



    } catch (FileNotFoundException e) {         
        e.printStackTrace();
    }

Each time through the while loop you reset the text to the newly read input, wiping out the previous text. 每次通过while循环时,您都将文本重置为新读取的输入,从而清除之前的文本。 You need to append the text, not set it. 您需要附加文本,而不是设置文本。

您正在while循环中覆盖jTextArea1中的文本

jTextArea1.setText(name); 

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

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