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

如何解决如何在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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-