我正在学习Java。我相信我在理解BufferedReader如何处理“ \ n”或“”字符串(换行符和空字符串)时遇到问题。
如果运行以下命令,则将这些字符串中的任何一个放入String数组都将失败。
String [] strings = {"55", "23", ""};
int total = 0;
for (String str : strings)
{
if (str != null) {
total += Integer.valueOf(str);
}
}
System.out.println(total);
很好,对我来说很有意义。对我来说没有意义的是当我在读取文件时运行此代码时。
BufferedReader reader = null;
int total = 0;
try {
reader = new BufferedReader(new FileReader("E:\\Testing\\Numbers.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
total += Integer.valueOf(line);
System.out.println("Total: " + total);
} catch(Exception e){
System.out.println(e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
使用具有以下内容的文本文件:
5
2
3
它运行没有错误。如果我在同一文件()中添加了一个空白行,它将失败并显示以下消息For input string: ""
我添加了isNumeric函数来解决此问题,但是我不理解为什么在运行没有任何空行的代码时BufferedReader可以工作,即使它不喜欢“ \ n”或“”字符串也是如此。我在javadocs中查询了valueOf(),却没有发现任何对我有帮助的东西。
这是我使用了isNumeric函数的最终代码,并显示了如何将“ \ n”和“”字符串视为非数字。
BufferedReader reader = null;
int total = 0;
try {
reader = new BufferedReader(new FileReader("E:\\Testing\\Numbers.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
if (isNumeric(line))
{
System.out.println(line);
total += Integer.valueOf(line);
}
System.out.println("Skipping a non numeric value");
}
System.out.println("Total: " + total);
} catch(Exception e){
System.out.println(e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public static boolean isNumeric(String str)
{
try
{
int d = Integer.parseInt(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
6
Skipping a non numeric value
1
Skipping a non numeric value
Skipping a non numeric value
2
Skipping a non numeric value
62
Skipping a non numeric value
23
Skipping a non numeric value
Total: 94
最终,我确实在该站点上看到了这篇文章,并且它很接近,但是我仍然无法弄清楚。
当使用BufferedReader时,readLine()方法将自动使用任何“换行符”字符。
因此,从本质上讲,您的初始文件是
5 \ n ...
在将字符串提供给代码之前,只需删除\ n即可。如果该行只是\ n; 那么你得到“”。一种简单的检查方法是line.isEmpty()
。
关于:我不明白为什么在运行没有空行的代码时BufferedReader可以工作;好吧,我不明白这个问题。如果您的代码只读取带数字的行,那么您坐在那里的代码可以处理空行也没关系。或包含“无效”数字文本的行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句