【问题标题】:Parsing txt file in java and returning a boolean在java中解析txt文件并返回一个布尔值
【发布时间】:2020-12-28 09:24:18
【问题描述】:

我正在尝试解析这样设置的 txt 文件

HBR - [false, true, false, true]
CKR - [false, false, false, true]
GFT - [true, true, false, true]

我想遍历每一行并返回一个布尔值 true 或 false。 这个布尔值是 3 个字母标识符是否存在于所述 txt 文件中。 这就是我到目前为止所得到的,我已经迷路了好几天了

public boolean bDoesLineExist() throws IOException {
    String file = "C:\\Parse\\alarmmasksettings.txt";
    FileInputStream fileInputStream = new FileInputStream(file);
    BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
    try {
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            String[] fields = line.split("-");
            if (fields[0].equals("HBR")) {
                return true
            } else {
                return false;
            }

        }
    } finally {
        reader.close();
    }

}

【问题讨论】:

  • 尝试调试并检查 fields 元素 - 拆分可能会留下尾随空格,因此比较失败。
  • 不是这样,它还在要求退货
  • 仍然要求退货是什么意思?

标签: java arrays string parsing


【解决方案1】:

我意识到您只是想确定特定的标识符是否包含在您要读取的数据文件中,但我认为在某些时候您可能想要获取该特定标识符的布尔设置。

你可以用一块石头杀死两只鸟(可以这么说),方法是创建一个方法来检索特定标识符的布尔设置,如果 标识符 可以' t 在文件中找到,然后返回 null 布尔数组。但是,如果在文件中找到 标识符,则返回设置的布尔数组。也许是这样的方法:

/**
 * Returns a boolean array containing the boolean settings for the supplied 
 * field name.<br>
 * 
 * @param settingsFor (String) The desired field name to get settings for.
 * 
 * @return (Boolean Array) Returns a boolean array containing the boolean 
 * settings for the supplied field name. Returns null is the field name is 
 * not found in file.
 */
public static boolean[] getMaskSettings(String settingsFor) {
    // Boolean Array to hold a specific field's boolean settings.
    boolean[] sets = null;  
    
    // 'Try With Resourses' used to to auto-close the reader.
    try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(
                new java.io.FileInputStream("alarmmasksettings.txt"), "UTF-8"))) {
        
        String line;
        // Read each file line until the End Of File (EOF)...
        while ((line = reader.readLine()) != null) {
            // Skip blank lines.
            if (line.trim().isEmpty()) {
                continue;
            }
            
            /* Split the currently read in file line into two spaecific
               parts, the field Name and the boolean Settings for that
               field.
            */
            
            String[] lineParts = line.replaceAll("[\\[\\]]", "").split("\\s{0,}\\-\\s{0,}");
            
            /* The first array element of lineParts[] should hold the field Name:
               Is the field name what was supplied (not case sensitive).  */
            if (lineParts[0].equalsIgnoreCase(settingsFor)) {
                // Yes it is...Split the second lineParts[] array element which
                // should be holding the boolean settings for the supplied field, 
                // into a String Array...
                String[] settingsStringArray = lineParts[1].split("\\s{0,},\\s{0,}");
                
                // Initialize the sets[] boolean array declared at the beginning of this method.
                sets = new boolean[settingsStringArray.length];
                
                /* Iterate through the settingsStringArray[] String array
                   and convert and apply the string representations of "true"
                   or "false" settings to their actual boolean value and 
                   apply them to the proper index in the sets[] boolean array. */
                for (int i = 0; i < settingsStringArray.length; i++) {
                    sets[i] = Boolean.parseBoolean(settingsStringArray[i]);
                }
                break;
            } 
        }
    }
    catch (UnsupportedEncodingException ex) {
        System.err.println(ex);
    }
    catch (IOException ex) {
        System.err.println(ex);
    }
    
    /* Since the sets[] boolean array was initially declared as null
       and if the desired field name was NOT found in file then the 
       sets[] arrays is never initialized and therefore is null and 
       this is what will be returned. If however the desired field 
       name was found in file then the sets[] array is initialized 
       and filled accordingly. 
    */
    return sets;
}

如何使用此方法:

String fieldName = "HBR";
boolean[] settings = getMaskSettings(fieldName);
if (settings == null) {
    System.out.println("The field name \"" + fieldName + "\" is not in file!");
}
else {
    System.out.print("Settings for the field name (" + fieldName + ") are: --> ");
    System.out.println(java.util.Arrays.toString(settings).replaceAll("[\\[\\]]", ""));
}

【讨论】:

    【解决方案2】:

    你可以试试这个

    if (fields[0].startsWith("HBR")) {
    

    而不是

     if (fields[0].equals("HBR")) {
    

    或者可以尝试-

     if (fields[0].trim().equals("HBR")) {
    

    因为你会在标记化的字符串中有空格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-14
      • 2021-05-04
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 2013-03-28
      • 2021-07-31
      相关资源
      最近更新 更多