.parseBoolean 结果为“false”,而 String 为“true”?

.parseBoolean turns out "false" with the String being "true"?

提问人:Leon Lozancic 提问时间:6/22/2023 更新时间:6/22/2023 访问量:78

问:

因此,我试图制作一个程序来读取.txt文件的内容,然后将其存储为布尔值

import java.io.FileReader;
import java.io.IOException;

public class StackOverflow {

    public static void main(String[] args) throws IOException {
        String textRead = "";
        FileReader fileReader = new FileReader("test.txt");
        char[] Array = new char[100];
        fileReader.read(Array);
        
        for(int i = 0; i<Array.length; i++) 
        {
            //if I were to print textRead it would print true
            textRead = textRead + Array[i];
        }
        //The .txt file contains only "true" and nothing else
        boolean test = Boolean.parseBoolean(textRead);
        //This prints out false for some reason
        System.out.print(test);
        
        fileReader.close();

    }

}

但是当我运行它时,它会打印出值“false”,即使应该只读的.txt包含“true”。

我尝试寻找解决方案,但并没有走得很远,因为我对 java 和一般编码还很陌生,谁能帮我解决这个问题?

文件阅读器 java-io

评论

0赞 g00se 6/22/2023
textRead = textRead.trim();您的字符串将充满冗余数组中的空值。你最好阅读台词
0赞 Leon Lozancic 6/22/2023
好的,谢谢。我不知道数组在字符串中留下空值。
0赞 g00se 6/22/2023
还要记住,解析布尔值很容易出错。例如: 将返回 .即使这是“真正的”;)System.out.println(Boolean.parseBoolean("This is garbage"));false
0赞 Leon Lozancic 6/22/2023
该死的,看起来我们这里有个喜剧演员
0赞 g00se 6/22/2023
是的,但这是一个严肃的笑话

答:

0赞 KameshG 6/22/2023 #1

public static boolean parseBoolean(String s) { return "true".equalsIgnoreCase(s); }

希望这能解释你的问题。 此外,char 数组中未使用的元素被视为 null

1赞 g00se 6/22/2023 #2

这其实就是你不修边幅的内容:String

00000000: 7472 7565 0a00 0000 0000 0000 0000 0000  true............
00000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000040: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000050: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000060: 0000 0000                                ....

与 C/C++ 等语言不同,Java 可以包含空字符。所以你需要阅读后,但正如我所说,最好阅读台词。话虽如此,无论您如何阅读它,致电都是明智的StringtextRead = textRead.trim();trim() ;)

1赞 Reilas 6/22/2023 #3

创建 char 数组时,它最初将包含 null 字符值。

char[] Array = new char[100];

因此,当您循环使用 Array 时,textRead 将附加 null char 值。

textRead = textRead + Array[i];

您可以通过在 for 循环中添加检查来避免这种情况。

for(int i = 0; i<Array.length; i++)
{
    if (Array[i] == '\u0000') break;

    //if I were to print textRead it would print true
    textRead = textRead + Array[i];
}

或者,可以使用 String 构造函数方法或 String#valueOf 方法来构造字符串。
随后,使用 String#trim 方法删除任何前导和尾随空格字符(包括 null 字符)。

textRead = new String(Array).trim();
textRead = String.valueOf(Array).trim();

值得注意的是,您可以使用具有 readLine 方法的 BufferedReader 类。

BufferedReader fileReader = new BufferedReader(new FileReader("test.txt"));
textRead = fileReader.readLine();
fileReader.close();
0赞 DevilsHnd - 退した 6/22/2023 #4

您已经(很好地)解释了任意声明数组来保存值的问题,您可能不知道读取整个布尔值文件可能需要多少元素,所以我不会在这里再次这样做。但是,我建议您根本不使用数组,而是使用 List 接口ArrayList 来保存文件行结果,这些结果可以动态增长并且最终不会充满 null元素(如果您不希望它)。

下面是一个如何使用列表接口的示例。请务必阅读代码中的注释。

应该注意的是,在此用例中,当读取文件行时,文件行会被修剪掉白色间距等。您还将注意到,String#matches() 方法与正则表达式 (regex) 字符串一起使用,以验证读取文件行包含“true”或“false”的事实。以下是所用正则表达式的简要说明:

  • (?i)忽略字母大小写;
  • true文件行仅包含“true”;
  • |
  • false文件行仅包含“false”;

再。。。阅读代码中的注释:

// List Interface to hold true/false file line results:
List<Boolean> list = new ArrayList<>();
    
/* `Try With Resources` used here to auto-close() the reader
   and free resources when done.        */
try (Scanner reader = new Scanner(new File("test.txt"))) {
    String line;
    while (reader.hasNextLine()) {
        line = reader.nextLine().trim();
        /* Any file line that contains anything other than
           true or false is ignored, including blank lines. */
        // Is the line true or false (not letter case sensitive):
        if (line.matches("(?i)true|false")) {
            // Convert line to boolean and add to List:
            list.add(Boolean.valueOf(line));
        }
    }

    // Convert list to an array if you like (after the reading):
    // Boolean[] array = list.toArray(new Boolean[0]);
        
    // Display List:
    for (Boolean bool : list) {
        System.out.println(bool);
    }
}
catch (FileNotFoundException ex) {
    System.err.println(ex.getMessage());
}