使用useDelimiter()连接子串

我的方法readDataFromFile()可以读取如下文本文件:

 Bird Golden Eagle Eddie Mammal Tiger Tommy Mammal Lion Leo Bird Parrot Polly Reptile Cobra Colin 

第一列是动物的’类型’,第二列是’物种’,第三列是’名称’。

电流输出:

 Bird Golden Eagle < (Golden and Eagle count as different substrings). Mammal Tiger Tommy Mammal Lion Leo Bird Parrot Polly Reptile Cobra Colin 
  • 我如何使用useDelimiter方法将“金鹰”算作一个物种?

现行代码:

 while(scanner.hasNextLine()) { String type = scanner.next(); String species = scanner.next(); String name = scanner.next(); System.out.println(type + " " + species + " " + name); scanner.nextLine(); addAnimal( new Animal(species, name, this) ); } 

第一行的“金鹰”两个都被一个标签分开

这是不正确的。

您的问题的来源显示列全部由制表符分隔( \t又称\u0009 ),但GoldenEagle空格字符( \u0020 )分隔。

不要使用Scanner读取您的文件。 它非常慢,不适合解析文件。 相反,使用BufferedReaderreadline()方法,然后split()split()为列。

演示

 try (BufferedReader in = Files.newBufferedReader(Paths.get("animals.txt"))) { for (String line; (line = in.readLine()) != null; ) { String[] values = line.split("\t"); for (String value : values) System.out.printf("%-15s", value); System.out.println(); } } 

产量

 Bird Golden Eagle Eddie Mammal Tiger Tommy Mammal Lion Leo Bird Parrot Polly Reptile Cobra Colin 

正如你所看到的, Golden Eagle文本没有被拆分。

您只需将正确的列分隔符设置为Scanner 表达式即可。 在下面的示例中,我将\t设置为列分隔符,使用\n作为新行分隔符:

 public static List readAnimals(InputStream in) { try (Scanner scan = new Scanner(Foo.class.getResourceAsStream("./animals.txt"))) { scan.useDelimiter("[\\t|\\n]"); List animals = new LinkedList<>(); while (scan.hasNext()) { animals.add(new Animal(scan.next(), scan.next(), scan.next())); } return animals; } }