【问题标题】:Find a specific line in a file, write that line and the 2 after to a new file在文件中查找特定行,将该行和之后的 2 写入新文件
【发布时间】:2016-02-09 11:46:04
【问题描述】:

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

它应该如何工作: 我进入一个菜单,其中列出了从数组列表中获取的员工,并询问我想要为谁“报告”的输入。我输入“John Doe”,程序创建一个名为“JDoe.txt”的“报告”,并在数组列表中搜索“John Doe”,并将他的名字连同他的信息一起写在新文件中(他名字后面的下两行同一个文件)。

我的代码正在创建“报告”并向其写入数据,但它只是写入数组列表中的第一个数据,而不是我输入的用户。如何为我输入的特定用户写作?

这是我拥有的一些代码,它们的方向正确,但没有产生我想要的东西,我似乎无法找到解决办法:

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();
    }
}

它正在读取的文件是什么样的:

【问题讨论】:

    标签: java arraylist collections bufferedreader bufferedwriter


    【解决方案1】:

    我发现了两个问题。第一个是在你完成并建立你的名字列表之后,你设置了 index = 0,它永远不会改变。

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

    这意味着你总是得到第一个值。如果将 index 设置为 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,因为我想到了它,您可以根据需要选择合适的类型。

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

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

    【讨论】:

    • 好的,我看到排序后的数组是如何导致问题的,并更改了我的代码,因此它不再排序,它能够完全按照我的意愿进行操作。 pastebin.com/LqDFaQvr 但是,我确实需要对员工列表进行排序,并且我知道地图可能会起作用,但是我还有其他不涉及使用地图的方向吗?
    • 您可以获取输入的名称并使用 for 循环搜索第一行,直到找到正确的索引,然后使用它。类似于: for (int i=0; i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2019-05-16
    • 2020-02-06
    相关资源
    最近更新 更多