简体   繁体   English

java String!= null无法从bufferedReader读取

[英]java String != null not working reading from bufferedReader

In android I am getting the String value from BufferedReader and it is null after reading from file. 在android中,我从BufferedReader获取String值,并且从文件读取后为null。

intstring = br.readLine();
System.out.println(intstring);
if(intstring != null)
{
      System.out.println("Inside if condition");
      int istring = Integer.parseInt(intstring);
}

My output is 我的输出是

 null
 Inside if condition
 NumberFormatException

Help me please 请帮帮我

Your NumberFormatException is happening because your input isn't a number. 您的NumberFormatException发生了,因为您输入的不是数字。 Maybe it's a blank line, or maybe it has some non-numeric characters. 可能是空白行,或者可能包含一些非数字字符。 In fact, your output suggests that it's actually the word "null" . 实际上,您的输出表明它实际上是单词"null"

You've got some options. 您有一些选择。

  • You could check that the string contains digits and no other characters before you parse it, for example by using a regular expression and a condition like if (intString.matches("\\\\d+")) . 您可以在解析字符串之前检查字符串是否包含数字,而不包含其他字符,例如,使用正则表达式和类似if (intString.matches("\\\\d+"))
  • You could catch the NumberFormatException , and do something particular when it happens. 您可以捕获NumberFormatException ,并在发生这种情况时做一些特别的事情。
  • You could check whether your string is blank, if you knew that there weren't going to be any non-numeric characters in the input. 如果您知道输入中不会包含任何非数字字符,则可以检查字符串是否为空。 For this option, you might write if (!intString.equals(""))) . 对于此选项,您可以编写if (!intString.equals("")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM