在文件中查找特定行,将该行和之后的 2 写入新文件

Find a specific line in a file, write that line and the 2 after to a new file

我需要在 .txt 文件中搜索特定行,例如某人的姓名,然后将姓名和接下来的 2 行是关于此人的数据写入新文件。

它应该如何工作: 我进入一个菜单,其中列出了从数组列表中提取的员工,并要求我输入我想要 "report" 的人。我输入 "John Doe" 程序创建一个名为 "JDoe.txt" 的 "report" 并在数组列表中搜索 "John Doe" 并将他的名字连同他的信息一起写入新文件(接下来的 2 行在同一文件中他的名字之后)。

我的代码正在创建 "report" 并向其写入数据,但它只是写入 arraylist 中第一个的数据,而不是我输入的特定用户的数据。我如何为我输入的特定用户写信?

这是我的一些代码,方向正确,但没有产生我想要的结果,我似乎无法找到解决方法:

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

import javax.swing.JOptionPane;

public class Report { // FirstName LastName, Programmer
    public Report() {
        // code here the logic to create a report for the user
        try {
            String empList = "";
            ArrayList<String> emps = new ArrayList<>();
            String[] firstLine = new String[100], secondLine = new String[100], thirdLine = new String[100];

            int index;

            FileReader file = new FileReader("payroll.txt");
            BufferedReader buffer = new BufferedReader(file);

            String line;

            for (index = 0; index < 100; index++) {
                firstLine[index] = "";
                secondLine[index] = "";
                thirdLine[index] = "";
            }

            index = 0;

            while ((line = buffer.readLine()) != null) {
                firstLine[index] = line;
                secondLine[index] = buffer.readLine();
                thirdLine[index] = buffer.readLine();
                emps.add(firstLine[index]);

                index++;
            }

            buffer.close();

            Collections.sort(emps);
            for (String str : emps) {
                empList += str + "\n";
            }

            String input = JOptionPane.showInputDialog(null, empList,
                    "Employee List", JOptionPane.PLAIN_MESSAGE);

            index = 0;

            // Iterate through the array containing names of employees
            // Check if a match is found with the input got from the user.
            // Break from the loop once you encounter the match.
            // Your index will now point to the data of the matched name

            if (emps.contains(input)) {

                JOptionPane.showMessageDialog(null, "Report Generated.",
                        "Result", JOptionPane.PLAIN_MESSAGE);

                String names[] = new String[2];
                names = input.split(" ");

                String fileName = names[0].charAt(0) + names[1] + ".txt";

                // Create a FileWritter object with the filename variable as the
                // name of the file.
                // Write the necessary data into the text files from the arrays
                // that
                // hold the employee data.
                // Since the index is already pointing to the matched name, it
                // will
                // also point to the data of the matched employee.
                // Just use the index on the appropriate arrays.

                File check1 = new File(fileName);
                FileWriter file2;
                if (check1.exists())
                    file2 = new FileWriter(fileName, true);
                else
                    file2 = new FileWriter(fileName);
                BufferedWriter buffer2 = new BufferedWriter(file2);

                buffer2.write("Name: " + firstLine[index]);
                buffer2.newLine();
                buffer2.write("Hours: " + secondLine[index]);
                buffer2.newLine();
                buffer2.write("Wage: " + thirdLine[index]);
                buffer2.newLine();
                buffer2.close();

            } else {
                JOptionPane.showMessageDialog(null, input + " does not exist");
                Report rpt = new Report();
            }

        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        new Report();
    }
}

它正在读取的文件看起来像什么:

我发现了两个问题。第一个是在你完成并建立你的名字列表之后,你设置了 index = 0,而且它从未改变过。

for (String str : emps) {
     empList += str + "\n";
}
//Make the JOptionPane...
index = 0;

这意味着您总是获得第一个值。如果将索引设置为 1,您将获得第二个值。您可以使用 ArrayList 库中的 indexOf(Object o) 方法在给定用户输入的名称的情况下获取正确的索引。示例:

int i = emps.indexOf(input);
buffer2.write("Name: " + firstline[i]);

但是,这只能部分解决问题,因为您在 emps 中对员工姓名列表进行了排序,而不是在您用来编写的数组中排序。

对此的一种解决方案是不对 emps 数组进行排序,这样可以使 indexOf 正确排序以正常工作,但 JOptionPane 中列出的员工将按照他们在文件中的顺序列出。

但是,由于为每个员工提供的值与该员工相关联,我建议使用将这些值与员工姓名相关联的数据结构,例如 Map。 (文档在这里:http://docs.oracle.com/javase/7/docs/api/java/util/Map.html)。

要初始化它,你可以这样使用它。我正在使用 linkedHashMap,因为它出现在我的脑海中,您可以 select 适合您需要的类型。

LinkedHashMap myMap<String, String[]> = new LinkedHashMap<String, String[]>();

第一个字段,String是你的Key,就是你员工的名字。 Value 是 String[],可以是具有所需两个值的数组。这将这些值与名称联系起来,确保它们不会丢失。要检查名称,只需使用 myMap.containsKey(name),并与 null 进行比较以查看它是否存在,然后使用 myMap.get(name) 获取该名称的条目。