在Java中解析txt文件并返回布尔值。

huangapple go评论73阅读模式
英文:

Parsing txt file in java and returning a boolean

问题

我正在尝试解析一个类似这样设置的txt文件:

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

我想循环遍历每一行,并返回一个布尔值,即true或false。这个布尔值表示这个三字母标识符是否存在于上述的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();
    }
}
英文:

Im trying to parse a txt file thats set up like this

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

I want to loop through each line and return a boolean of true or false.
This boolean is whether or not the 3 letter identifier exists in said txt file.
This is what I got so far, Ive been lost for days

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();
    }

}

答案1

得分: 0

可以尝试这样写:

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

而不是

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

或者尝试使用:

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

因为在分词后的字符串中可能会有空格。

英文:

can you try this

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

instead of

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

or may be try -

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

as you would have space in the tokenized string

答案2

得分: 0

我意识到您只想确定特定的标识符是否包含在要读取的数据文件中,但我认为在某些时候您可能希望获取该特定标识符的布尔设置。您可以一举两得地通过创建一个方法来检索特定标识符的布尔设置,如果在文件中找不到标识符,则返回null布尔数组。但如果在文件中找到标识符,则返回设置的布尔数组。也许可以创建一个类似以下的方法:

/**
 * 返回一个布尔数组,其中包含所提供字段名称的布尔设置。<br>
 * 
 * @param settingsFor(String)要获取设置的所需字段名称。
 * 
 * @return(布尔数组)返回一个布尔数组,其中包含所提供字段名称的布尔设置。如果在文件中未找到字段名称,则返回null。
 */
public static boolean[] getMaskSettings(String settingsFor) {
    // 布尔数组,用于保存特定字段的布尔设置。
    boolean[] sets = null;  
    
    // 使用“Try With Resourses”来自动关闭读取器。
    try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(
                new java.io.FileInputStream("alarmmasksettings.txt"), "UTF-8"))) {
        
        String line;
        // 读取每行文件直到文件末尾(EOF)...
        while ((line = reader.readLine()) != null) {
            // 跳过空行。
            if (line.trim().isEmpty()) {
                continue;
            }
            
            /* 将当前读取的文件行分为两个特定部分,
               字段名称和该字段的布尔设置。
            */
            
            String[] lineParts = line.replaceAll("[\\[\\]]", "").split("\\s{0,}\\-\\s{0,}");
            
            /* lineParts[]的第一个数组元素应该保存字段名称:
               字段名是否与所提供的相同(不区分大小写)。  */
            if (lineParts[0].equalsIgnoreCase(settingsFor)) {
                // 是的...将第二个lineParts[]数组元素分割为一个字符串数组,
                // 该数组应该保存所提供字段的布尔设置。
                String[] settingsStringArray = lineParts[1].split("\\s{0,},\\s{0,}");
                
                // 初始化在方法开头声明的sets[]布尔数组。
                sets = new boolean[settingsStringArray.length];
                
                /* 遍历settingsStringArray[]字符串数组,
                   将“true”或“false”设置的字符串表示转换并应用为实际的布尔值,
                   并将它们应用于sets[]布尔数组中的适当索引。 */
                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);
    }
    
    /* 由于sets[]布尔数组最初被声明为null,
       如果在文件中找不到所需字段名称,则sets[]数组永远不会被初始化,
       因此为null,这将被返回。但如果在文件中找到所需字段名称,
       则sets[]数组被初始化并相应地填充。 
    */
    return sets;
}

如何使用此方法:

String fieldName = "HBR";
boolean[] settings = getMaskSettings(fieldName);
if (settings == null) {
    System.out.println("字段名称 \"" + fieldName + "\" 不在文件中!");
}
else {
    System.out.print("字段名称(" + fieldName + ")的设置是: --> ");
    System.out.println(java.util.Arrays.toString(settings).replaceAll("[\\[\\]]", ""));
}
英文:

I realize that you just want to determine if a specific identifier is contained within the data file you want to read but I should think that at some point you may want to obtain the boolean settings for that specific identifier.

You can kill two birds with one stone (so to speak) by creating a method to retrieve the the boolean settings for a specific identifier and if the identifier can't be found in file then null boolean array is returned. If however the identifier is found in file then a boolean array of the settings is returned. Perhaps a method something like this:

/**
* Returns a boolean array containing the boolean settings for the supplied 
* field name.&lt;br&gt;
* 
* @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&#39;s boolean settings.
boolean[] sets = null;  
// &#39;Try With Resourses&#39; used to to auto-close the reader.
try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(
new java.io.FileInputStream(&quot;alarmmasksettings.txt&quot;), &quot;UTF-8&quot;))) {
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(&quot;[\\[\\]]&quot;, &quot;&quot;).split(&quot;\\s{0,}\\-\\s{0,}&quot;);
/* 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(&quot;\\s{0,},\\s{0,}&quot;);
// 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 &quot;true&quot;
or &quot;false&quot; settings to their actual boolean value and 
apply them to the proper index in the sets[] boolean array. */
for (int i = 0; i &lt; 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;
}

How you might use this method:

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

huangapple
  • 本文由 发表于 2020年9月10日 06:09:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63820206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定