【发布时间】:2020-01-07 18:28:48
【问题描述】:
我在尝试从文件读取到 Java 时遇到了一个奇怪的问题。只要输入文件末尾有一个空行,我就可以读取文件中的所有内容。如果没有空行,它会崩溃。这是为什么呢?
我发现问题是一段时间后的空白行。只要输入文件末尾有空行就可以了。
可以正常运行的输入文件:
会报错的输入文件:
注意行号!
public static void main(String[] args) {
String fileInputName;
String fileOutputName;
String firstName;
String lastName;
String houseNumber;
String street;
String city;
String state;
String zip;
String productDescription;
double productPrice = 0;
double productCost = 0;
int productQuantity = 0;
int totalQuantity = 0;
double totalCost = 0;
Scanner input = null;
input = new Scanner(System.in);
System.out.printf("What is the file name?\n");
fileInputName = input.nextLine();
System.out.println("File name is: " + fileInputName);
FileReader filereader;
Scanner readInput = null;
try {
readInput = new Scanner(new FileReader(fileInputName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Header
firstName = readInput.nextLine();
lastName = readInput.nextLine();
houseNumber = readInput.nextLine();
street = readInput.nextLine();
city = readInput.nextLine();
state = readInput.nextLine();
zip = readInput.nextLine();
System.out.printf("Purchase Report\n---------------\n%s %s\n%s %s\n%s, %s %s\n\n"
+ "Description\t\t\tPrice\tQuantity\tCost\n"
+ "-----------\t\t\t-----\t--------\t----\n",
firstName, lastName, houseNumber, street, city, state, zip);
while (readInput.hasNextLine())
{
productDescription = readInput.nextLine();
productPrice = readInput.nextDouble();
readInput.nextLine();
productQuantity = readInput.nextInt();
readInput.nextLine();
productCost = productPrice * productQuantity;
totalCost += productCost;
totalQuantity += productQuantity;
System.out.printf("%-30s%7.2f\t%8d %7.2f\n",
productDescription, productPrice, productQuantity, productCost);
}
//Footer
System.out.printf("-----------\t\t\t-----\t--------\t----\n"
+ "Total\t\t\t\t\t%8d %7.2f\n", totalQuantity, totalCost);
readInput.close();
}
}
它应该能够在没有额外的行的情况下阅读对吧?谁能向我解释发生了什么以及如何解决它?谢谢!
【问题讨论】:
-
好吧,在读取最后一个产品数量后,您调用 nextLine() 而不首先检查是否有下一行。而且没有。所以你得到了那个例外。
-
这是有道理的。那么我应该再做一个循环来检查是否有下一行吗?如果是这样,我会怎么做?我是 Java 语法的新手,所以我不太确定。
标签: java file-io java.util.scanner inputstream