BufferedReader 在行中找到特定的单词,从该行中获取数据

BufferedReader found specific word in line, take the data from that line

 br = new BufferedReader(new FileReader(file));

        while ((finalLine = br.readLine()) != null) {

            String[] reader = finalLine.split(",");

            String foundWord = "dod";

             for (String word : reader) {
              if (word.equals(foundWord)) {

              String NAME = reader[0];
              String PASSWORD = reader[1];
              String CONTACT_NO = reader[2];
              String EMAIL_ADDRESS = reader[3];

我目前正在使用 BufferedReader 从文本文件中读取所有行,如果找到 "dod" 如何在同一行中获取其余信息 1。请帮助。

这些行将有

(line 1) dod, 12345, 00112949, test@testacc.com 
(line 2) abc, 22222, 0004993, aaa@aaaac.com

在文本文件中,如果从上面的代码中找到 dod,我想提取第 1 行数据并保存在变量中。

请试试这个代码:

public static void main(String[] args) {
        BufferedReader reader = null;
        String line;
        String name,pwd,contactNo,email;
        try {
            reader = new BufferedReader(new FileReader("src/files/temp2.txt"));
            String foundWord = "dod";
            while ((line = reader.readLine()) != null) {
                String[] words = line.split(",");
                for (String word : words) {
                    if (word.equals(foundWord)) {
                        name = words[0];
                        pwd = words[1];
                        contactNo = words[2];
                        email = words[3];
                        System.out.println("Details: " +name + "-" + pwd + "-" + contactNo + "-" + email);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
             reader.close()
        }
    }

输出将是: Details: dod-12345-00112949-test@testacc.com。如果需要,您可以将该信息存储在一个对象中。

看看这个:

 public class A {

    public static void main(String[] args) throws FileNotFoundException {

        boolean found = false;
        Scanner line = new Scanner(new File("E:/temp.txt"));
        String foundWord = "dod";
        while (line.hasNextLine()) {

            String[] reader = line.nextLine().split(",");

            for (String word : reader) {
                if (word.equals(foundWord)) {

                    found = true;
                    String NAME = reader[0];
                    String PASSWORD = reader[1];
                    String CONTACT_NO = reader[2];
                    String EMAIL_ADDRESS = reader[3];
                    System.out.println(NAME + "\t" + PASSWORD + "\t"
                            + CONTACT_NO + "\t" + EMAIL_ADDRESS);
                }

            }

        }
        if (!found) {
            System.out.println(foundWord + " not found");
        }
    }

}

已添加如果未找到条件

输出:

dod  12345   00112949    test@testacc.com 

if found "dod" how to get the rest of the information in the same line

您已经有了它,在 finalLine 变量中。