import java.util.*;
public void readToolData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
scanner.useDelimiter(",");
while( scanner.hasNext() )
{
String toolName = scanner.next();
String itemCode = scanner.next();
int timesBorrowed = scanner.nextInt();
boolean onLoan = scanner.nextBoolean();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
storeTool(new Tool(toolName, itemCode, timesBorrowed, onLoan, cost, weight));
}
scanner.close();
}
文件:
Makita BHP452RFWX,RD2001, 12 ,false,14995,1800
Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
Bosch GSR10.8-Li Drill Driver,RD3021,25, true,9995,820
Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400
发布于 2020-02-20 18:59:00
您应该更改分隔符,使其包含逗号周围的可选空格以及换行符。如下所示:
scanner.useDelimiter("(\\s*,\\s*)|(\r\n)|(\n)");
发布于 2020-02-20 19:05:51
您将获得输入文件第一行的int timesBorrowed = scanner.nextInt()
格式的InputMismatchException。该错误是由逗号周围的空格引起的。
将分隔符更改为*, *
,然后逗号周围的任意数量的空格将成为分隔符的一部分,从而被删除。除了空格,您还可以使用\\s
,它覆盖了所有空格(空格和制表符)。
然后,您将在输入文件的第一行的int weight = scanner.nextInt()
行中再次获得异常,因为1800
后面跟着一个换行符。因此,您需要一个也与换行符匹配的分隔符:( *, *)|[\r\n]+
正则表达式的意思是:由任意数量的空格组成的逗号或至少一个连续的换行符。请注意,Unix文件通常只有\n
,而Windows文件的每个换行符通常都有两个字符\r\n
。因此该表达式涵盖了这两种文件格式,还跳过了空行。
下面是一个完整的例子,它是有效的:
public class Main
{
public static void readToolData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
scanner.useDelimiter("( *, *)|[\r\n]+");
while (scanner.hasNext())
{
String toolName = scanner.next();
String itemCode = scanner.next();
int timesBorrowed = scanner.nextInt();
boolean onLoan = scanner.nextBoolean();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
System.out.println("toolName=" + toolName + ", weight=" + weight);
}
scanner.close();
}
public static void main(String[] args) throws FileNotFoundException
{
readToolData("/home/stefan/Programmierung/PC-Java/test/src/test.txt");
}
}
发布于 2020-02-20 18:53:35
这里的问题是,您的行不是以逗号结尾,而是有换行符。
这是您的程序对输入的前两行的解释:
Makita BHP452RFWX,RD2001, 12 ,false,14995,1800\nFlex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
注意到1800之后没有逗号了吗?有一个表示换行符的\n
。
编辑:我也注意到一些逗号后面的空格,所以这可能也会把事情搞乱。尝试Eng.Fuad的答案,因为它解决了我关心的问题。
https://stackoverflow.com/questions/60326657
复制