【发布时间】: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