使用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
),但Golden
和Eagle
由空格字符( \u0020
)分隔。
不要使用Scanner
读取您的文件。 它非常慢,不适合解析文件。 相反,使用BufferedReader
和readline()
方法,然后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; } }