如何在Java中打印文件中两个空行之间的所有内容?

如何在Java中打印文件中两个空行之间的所有内容?,java,bufferedreader,filereader,jtextarea,Java,Bufferedreader,Filereader,Jtextarea,因此,我正在制作一个应用程序,其中我将客户的详细信息(如姓名、姓氏、出生日期、ID和地址)保存到一个名为“clientListFile.txt”的文件中。每次向文件中添加客户机信息时,信息前后都有一个空白,如下所示: //empty line //empty line fn sn 1900-08-01 1234 addressname s 8 hn a pc t country

因此,我正在制作一个应用程序,其中我将客户的详细信息(如姓名、姓氏、出生日期、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;
}

在这个定制的CSV文件中,数据的布局更像一个表格,记录更清晰,即使只是读取文件本身。如果你想让你的客户机类做这类事情,那就发电子邮件给我。

你已经说明了你的要求。现在你的问题是什么?是什么阻止了您实现该功能?例如,您可以在迭代时将一个条目的所有行存储到列表中,每当您传递这两个空行以开始一个新条目时重置列表,然后在条目中找到匹配项时打印列表。谢谢您的回复。问题是我不知道如何实现或如何编写代码。我提出了一系列想法,包括你的想法,但我甚至不知道从哪里开始。一种可能是将整个输入文件读入客户机实例列表,其中客户机类包含客户机的所有信息,使用该列表在GUI中显示客户机,然后在应用程序结束时写出整个列表。
但是,我希望它打印出名为“jDisplaySearchedClientsTextArea”的JTextArea中前两个空行和最后两个空行之间的所有内容。
您可以说明要执行的操作的逻辑。现在您需要在代码中实现该逻辑。您需要测试一个空行,然后当该行不为空时打印出您的信息,然后如果有另一个空行,则退出循环。
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