如何解决如何在Java文件中打印出两个空行之间的所有内容?
因此,我正在制作一个应用程序,其中将客户的详细信息(例如名字,姓氏,DOB,ID和地址)保存到名为“ clientListFile.txt”的文件中。每次将客户信息添加到文件中时,信息之前和之后都有一个空白,如下所示:
//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”,它将打印出它所在的行。但是,我希望它在前两个空行和最后两个空行之间打印出JTextArea中称为“ jDisplaySearchedClientsTextArea”的所有内容。
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 类。即使使用文件类型的数据存储方法(就像您正在使用的那样),您也确实希望Client类保持该数据的有条理并以CSV样式( C omma S 分隔的 V 文件)。以下是 自定义 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,1964-11-30,her-email@yahoo.com,604-776-3466
1236,Jack,Naso,1993-03-18,33912 CrackShack Ave,Vancouver,British Columbia,V2Z1D2,myemailaddy@hotmail.com,856-302-1122
1237,William,Shakaconn,1996-12-13,1212 Playwrite Street,Langely,V2T4C9,playme@gmail.ca,777-664-9351
在此自定义CSV文件中,数据的放置方式更像表,并且即使仅读取文件本身,记录也更清晰。如果您希望您的Client类执行此类操作,请给我发送电子邮件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。