Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

java - Using useDelimiter() to join substrings

My method readDataFromFile() can read text files like:

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

The first column is the 'Type' of animal, second column is 'Species' and third is 'Name'.

Current Output:

Bird  Golden Eagle  < (Golden and Eagle count as different substrings).
    Mammal  Tiger Tommy
    Mammal  Lion Leo
    Bird  Parrot Polly
    Reptile  Cobra Colin
  • How would I use the useDelimiter method to make 'Golden Eagle' count as one species?

Current Code:

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) );
       }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the first line has 'Golden Eagle' both separated by a tab

That is not correct.

The source of your question shows that the columns are all separated by a tab character ( aka u0009), but Golden and Eagle are separated by a space character (u0020).

Do not read your file using Scanner. It is very slow and not the appropriate tool for parsing your file. Instead, use a BufferedReader and the readline() method, then split() the line into columns.

Demo

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

Output

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

As you can see, the Golden Eagle text did not get split.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...