如何从 Java 中的文件中打印出两个空行之间的所有内容?
How can I print out everything between two empty lines from a file in Java?
所以,我正在制作一个应用程序,我将名字、姓氏、DOB、ID 和地址等客户的详细信息保存到名为“clientListFile.txt”的文件中。每次在文件中添加客户信息时,信息前后都有一个空的space,如下所示:
//empty line
//empty line
fn
sn
1900-08-01
1234
addressname
s
8
hn
a
pc
t
country
//empty line
//empty line
fn1
sn1
1900-08-02 ... (etc)
在下面的代码中,我可以找到文件中是否存储了一个字符串。例如,在我的程序中,如果我搜索“fn”或搜索“1234”,它会打印出它位于哪一行。但是,我希望它在前两个空行和最后两个空行之间打印出名为“jDisplaySearchedClientsTextArea”的 JTextArea 中的所有内容。
private void jSearchClientsButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fn = jClientsFNTextField.getText();
String clientListFile = "clientListFile.txt";
try {
BufferedReader areader = new BufferedReader(new FileReader(new File(clientListFile)));
Scanner scanner = new Scanner(clientListFile);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (fn.equals(areader.readLine())) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
}
catch (IOException ioe) {
System.out.println("Error while saving Head Office Address");
}
}
您可以使用类似这样的方法:
/**
* Parses and searches a "clientListFile.txt" data file based on the supplied
* search criteria.<br>
*
* @param dataFilePath (String) The full path and file name of the data file
* to search in.<br>
*
* @param searchCriteria (String) What to search for in each data record
* contained within the supplied data file.<br>
*
* @param useContains (Optional - Boolean - Default is True) This optional
* parameter by default is boolean '<b>true</b>'. This means that every search
* done in any data file record is carried out by locating the search criteria
* (ignoring letter case) within any record field value location that <u><b>contains</b></u>
* the search criteria. An example
* of this would be:<pre>
*
* Search Criteria: "fred"
*
* A Data Record:
* =============
* First Name: Danny (No Match)
* Surname: Fredrikson (Match - Fred......)
* Birthdate: 1957-11-07 (No Match)
* Cient ID: 1234 (No Match)
* Address: 3233 Sandy St. (No Match)
* City: Fredericton (Match - Fred.......)
* Province: New Brunswick (No Match)
* etc.....</pre><br>
*
* If boolean '<b>false</b>' is optionally supplied then the search is done
* based on <u><b>equality</b></u>. This means that every search done in any data file
* record is carried out by locating the search criteria within any record
* field value that is <b>equal to</b> (ignoring letter case) the supplied
* search criteria. An example of this would be:<pre>
*
* Search Criteria: "fred"
*
* A Data Record:
* =============
* First Name: Fred (Match - Fred)
* Surname: Fredrikson (No Match)
* Birthdate: 1957-11-07 (No Match)
* Cient ID: 1234 (No Match)
* Address: 3233 Sandy St. (No Match)
* City: Fredericton (No Match)
* Province: New Brunswick (No Match)
* etc.....</pre><br>
*
* @return A List Interface Object of Type String - {@code List<String>}.
*/
public static List<String> searchInRecords(String dataFilePath, String searchCriteria, boolean... useContains) {
boolean UseCONTAINSinSearches = true;
if (useContains.length > 0) {
UseCONTAINSinSearches = useContains[0];
}
int fileLinesCounter = 0;
int fieldsCounter = 0;
int dataRecordsCounter = 0;
int criterialFoundRecords = 0;
boolean inRecord = false;
List<String> foundRecords = new ArrayList<>();
String[] fields = new String[12];
// 'Try With Resources' use here to auto-close the reader.
try (BufferedReader reader = new BufferedReader(new FileReader(dataFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
fileLinesCounter++;
line = line.trim();
if (line.isEmpty() && fieldsCounter == 0) {
inRecord = true;
}
else if (inRecord && fieldsCounter <= 11) {
fields[fieldsCounter] = line;
if (fieldsCounter == 11) {
String record = new StringBuilder("").append(fields[0]).append(", ")
.append(fields[1]).append(", ").append(fields[2]).append(", ")
.append(fields[3]).append(", ").append(fields[4]).append(", ")
.append(fields[5]).append(", ").append(fields[6]).append(", ")
.append(fields[7]).append(", ").append(fields[8]).append(", ")
.append(fields[9]).append(", ").append(fields[10]).append(", ")
.append(fields[11]).toString();
dataRecordsCounter++;
// Search Type 1 (using CONTAINS where criteria is anywhere in a field)
if (UseCONTAINSinSearches) {
for (String field : fields) {
if (field == null) { continue; }
if (field.toLowerCase().contains(searchCriteria)) {
if (!foundRecords.contains(record)) {
foundRecords.add(record);
criterialFoundRecords++;
}
}
}
}
// Search Type 2 (using exact match to field but ignoring letter case)
else {
for (String field : fields) {
if (field == null) { continue; }
if (field.equalsIgnoreCase(searchCriteria)) {
if (!foundRecords.contains(record)) {
foundRecords.add(record);
criterialFoundRecords++;
}
}
}
}
}
fieldsCounter++;
}
else {
fieldsCounter = 0;
inRecord = false;
}
}
}
// Handle the exceptions (if any) any way you see fit.
catch (FileNotFoundException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
/* The following integer type variables can be used to supply related
class member variables. They serve no specific purpose within this
method and can be removed if desired. Sometimes this information can
be handy. */
System.out.println("Overall Number of Data File Lines: --> " + fileLinesCounter);
System.out.println("Overall Number of Records in File: --> " + dataRecordsCounter);
System.out.println("Criterial Search - Records Found: --> " + criterialFoundRecords);
return foundRecords;
}
当然,使用数据库来处理这类事情并使用 Client class 会更好。即使使用文件类型数据存储方法(就像您正在使用的那样),您也确实希望客户端 class 来组织数据并将数据存储得更像 CSV 样式 (Comma S分离了 Values) 文件。下面是一个 custom CSV 数据文件的例子:
Client ID, First Name, Sir Name, Date Of Birth, Address, City, State/Province, Postal Code, Country, E-Mail, Phone Number
=======================================================================================================================================================================================
1234, Fred, Flinstone, 1957-11-07, 2977 Oriole Cooky Way, Bedrock, Stones Throw, V2Q5W8, Canada, his-email@yahoo.com, 604-776-1121
1235, Wilma, Flinstone, 1964-11-30, 2977 Oriole Cooky Way, Bedrock, Stones Throw, V2Q5W8, Canada, her-email@yahoo.com, 604-776-3466
1236, Jack, Naso, 1993-03-18, 33912 CrackShack Ave, Vancouver, British Columbia, V2Z1D2, Canada, myemailaddy@hotmail.com, 856-302-1122
1237, William, Shakaconn, 1996-12-13, 1212 Playwrite Street, Langely, British Columbia, V2T4C9, Canada, playme@gmail.ca, 777-664-9351
在这个自定义的 CSV 文件中,数据的布局更像 table,即使只是读取文件本身,记录也更清晰。如果你想让你的客户 class 做这种事,那么就 E-Mail 我。
所以,我正在制作一个应用程序,我将名字、姓氏、DOB、ID 和地址等客户的详细信息保存到名为“clientListFile.txt”的文件中。每次在文件中添加客户信息时,信息前后都有一个空的space,如下所示:
//empty line
//empty line
fn
sn
1900-08-01
1234
addressname
s
8
hn
a
pc
t
country
//empty line
//empty line
fn1
sn1
1900-08-02 ... (etc)
在下面的代码中,我可以找到文件中是否存储了一个字符串。例如,在我的程序中,如果我搜索“fn”或搜索“1234”,它会打印出它位于哪一行。但是,我希望它在前两个空行和最后两个空行之间打印出名为“jDisplaySearchedClientsTextArea”的 JTextArea 中的所有内容。
private void jSearchClientsButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String fn = jClientsFNTextField.getText();
String clientListFile = "clientListFile.txt";
try {
BufferedReader areader = new BufferedReader(new FileReader(new File(clientListFile)));
Scanner scanner = new Scanner(clientListFile);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (fn.equals(areader.readLine())) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
}
catch (IOException ioe) {
System.out.println("Error while saving Head Office Address");
}
}
您可以使用类似这样的方法:
/**
* Parses and searches a "clientListFile.txt" data file based on the supplied
* search criteria.<br>
*
* @param dataFilePath (String) The full path and file name of the data file
* to search in.<br>
*
* @param searchCriteria (String) What to search for in each data record
* contained within the supplied data file.<br>
*
* @param useContains (Optional - Boolean - Default is True) This optional
* parameter by default is boolean '<b>true</b>'. This means that every search
* done in any data file record is carried out by locating the search criteria
* (ignoring letter case) within any record field value location that <u><b>contains</b></u>
* the search criteria. An example
* of this would be:<pre>
*
* Search Criteria: "fred"
*
* A Data Record:
* =============
* First Name: Danny (No Match)
* Surname: Fredrikson (Match - Fred......)
* Birthdate: 1957-11-07 (No Match)
* Cient ID: 1234 (No Match)
* Address: 3233 Sandy St. (No Match)
* City: Fredericton (Match - Fred.......)
* Province: New Brunswick (No Match)
* etc.....</pre><br>
*
* If boolean '<b>false</b>' is optionally supplied then the search is done
* based on <u><b>equality</b></u>. This means that every search done in any data file
* record is carried out by locating the search criteria within any record
* field value that is <b>equal to</b> (ignoring letter case) the supplied
* search criteria. An example of this would be:<pre>
*
* Search Criteria: "fred"
*
* A Data Record:
* =============
* First Name: Fred (Match - Fred)
* Surname: Fredrikson (No Match)
* Birthdate: 1957-11-07 (No Match)
* Cient ID: 1234 (No Match)
* Address: 3233 Sandy St. (No Match)
* City: Fredericton (No Match)
* Province: New Brunswick (No Match)
* etc.....</pre><br>
*
* @return A List Interface Object of Type String - {@code List<String>}.
*/
public static List<String> searchInRecords(String dataFilePath, String searchCriteria, boolean... useContains) {
boolean UseCONTAINSinSearches = true;
if (useContains.length > 0) {
UseCONTAINSinSearches = useContains[0];
}
int fileLinesCounter = 0;
int fieldsCounter = 0;
int dataRecordsCounter = 0;
int criterialFoundRecords = 0;
boolean inRecord = false;
List<String> foundRecords = new ArrayList<>();
String[] fields = new String[12];
// 'Try With Resources' use here to auto-close the reader.
try (BufferedReader reader = new BufferedReader(new FileReader(dataFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
fileLinesCounter++;
line = line.trim();
if (line.isEmpty() && fieldsCounter == 0) {
inRecord = true;
}
else if (inRecord && fieldsCounter <= 11) {
fields[fieldsCounter] = line;
if (fieldsCounter == 11) {
String record = new StringBuilder("").append(fields[0]).append(", ")
.append(fields[1]).append(", ").append(fields[2]).append(", ")
.append(fields[3]).append(", ").append(fields[4]).append(", ")
.append(fields[5]).append(", ").append(fields[6]).append(", ")
.append(fields[7]).append(", ").append(fields[8]).append(", ")
.append(fields[9]).append(", ").append(fields[10]).append(", ")
.append(fields[11]).toString();
dataRecordsCounter++;
// Search Type 1 (using CONTAINS where criteria is anywhere in a field)
if (UseCONTAINSinSearches) {
for (String field : fields) {
if (field == null) { continue; }
if (field.toLowerCase().contains(searchCriteria)) {
if (!foundRecords.contains(record)) {
foundRecords.add(record);
criterialFoundRecords++;
}
}
}
}
// Search Type 2 (using exact match to field but ignoring letter case)
else {
for (String field : fields) {
if (field == null) { continue; }
if (field.equalsIgnoreCase(searchCriteria)) {
if (!foundRecords.contains(record)) {
foundRecords.add(record);
criterialFoundRecords++;
}
}
}
}
}
fieldsCounter++;
}
else {
fieldsCounter = 0;
inRecord = false;
}
}
}
// Handle the exceptions (if any) any way you see fit.
catch (FileNotFoundException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
/* The following integer type variables can be used to supply related
class member variables. They serve no specific purpose within this
method and can be removed if desired. Sometimes this information can
be handy. */
System.out.println("Overall Number of Data File Lines: --> " + fileLinesCounter);
System.out.println("Overall Number of Records in File: --> " + dataRecordsCounter);
System.out.println("Criterial Search - Records Found: --> " + criterialFoundRecords);
return foundRecords;
}
当然,使用数据库来处理这类事情并使用 Client class 会更好。即使使用文件类型数据存储方法(就像您正在使用的那样),您也确实希望客户端 class 来组织数据并将数据存储得更像 CSV 样式 (Comma S分离了 Values) 文件。下面是一个 custom CSV 数据文件的例子:
Client ID, First Name, Sir Name, Date Of Birth, Address, City, State/Province, Postal Code, Country, E-Mail, Phone Number
=======================================================================================================================================================================================
1234, Fred, Flinstone, 1957-11-07, 2977 Oriole Cooky Way, Bedrock, Stones Throw, V2Q5W8, Canada, his-email@yahoo.com, 604-776-1121
1235, Wilma, Flinstone, 1964-11-30, 2977 Oriole Cooky Way, Bedrock, Stones Throw, V2Q5W8, Canada, her-email@yahoo.com, 604-776-3466
1236, Jack, Naso, 1993-03-18, 33912 CrackShack Ave, Vancouver, British Columbia, V2Z1D2, Canada, myemailaddy@hotmail.com, 856-302-1122
1237, William, Shakaconn, 1996-12-13, 1212 Playwrite Street, Langely, British Columbia, V2T4C9, Canada, playme@gmail.ca, 777-664-9351
在这个自定义的 CSV 文件中,数据的布局更像 table,即使只是读取文件本身,记录也更清晰。如果你想让你的客户 class 做这种事,那么就 E-Mail 我。