Skip to main content
Logo image

Section 11.2 Data from files

Files are used to store data in software that we use every day. For example, when you play a game on your computer, your game progress is saved in a file. The next time you play that game, your game progress is loaded in from that file, so you can continue where you left off. In this lesson, you will learn how to read in data from a file in Java.
A file is storage for data that persists when the program is not running. The data in a file can be retrieved during program execution. For example in Sectionย 6.2ย Looping over arrays, you created a SpellChecker class that reads in a dictionary file into an array of words, and a spellcheck method that uses this array to verify if a word is spelled correctly. Input files like the dictionary enable us to handle large amounts of data efficiently. Instead of manually entering data into our program every time it runs, we can store the data in a file and read it as needed. Another benefit of using files is the ability to separate the data from the code, allowing for more modular and flexible software design.

Subsection 11.2.1 File and Scanner

These days there are two sets of classes for interacting with files from Java. Weโ€™ll start with the more traditional way which is part of the AP curriculum. Then later weโ€™ll look at a more modern and slightly more convenient way.
The first thing we need is an object to represent a file on our computer. The traditional wayโ€”and the AP wayโ€”is with the class File in the package java.io. The io in the package name stands for I/O which is itself an abbreviation for Input/Output since the classes in that package are all related to moving data into a program (input) and back out (output).
A File object can be constructed with a contstructor that takes a String containing the name of the file. For example if we want to use a file named data.txt we can construct a File object like this:
import java.io.*;
...
File dataFile = new File("data.txt");
At this point the file doesnโ€™t even need to exist. We just have a way to refer to such a file. But if it does exist and we want to read data from it we need to open the file with some object that knows how to read data from it. There are a number of classes in Java for doing that depending on how we want to access the data. In the AP curriculum we use the class Scanner which is in the package java.util, the same package as ArrayList. If we construct a Scanner with a File object as an argument we get a Scanner that we can use to read data from the file on our harddrive.
import java.io.*;
import java.util.*;
...
File dataFile = new File("data.txt");
Scanner data = new Scanner(dataFile);
A single Scanner can be used repeatedly to read from the same file. It has a number of methods that will each read different data from the underlying file and it keeps track of where it left off so calling the same method multiple times will probably return different things each time as the Scanner advances through the file.
The simplest of these methods to use is nextLine which reads the next complete line from the file, up to the next newline character or the end of the file and returns it as a String with the newline removed. Often, as weโ€™ll see in the next section, the easiest way to read data from a file is to read it a line at a time and then use various methods on String and the wrapper classes Integer and Double to take apart the String and convert the parts to the data types we actually want.
But Scanner does provide some other methods that are part of the AP curriculum ande are listed on the Java Quick Reference.
  • nextInt - reads the next bit of text and tries to parse it as an int value.
  • nextDouble - reads the next bit of text and tries to parse it as a double value.
  • nextBoolean - reads the next bit of text and tries to parse it as an boolean value.
  • next - reads and return the next token as a String
  • hasNext - returns true if there is another token to read
  • close - closes the Scanner and the underlying file so no more data can be read from it
In practice the methods other than nextLine are tricky to use because of the way the Scanner decides whether thereโ€™s another token. One method that is not part of the AP curriculum but which goes very well with nextLine is hasNextLine which returns a boolean indicating whether it is possible got get another line with nextLine.
For instance if we wanted to load all the lines from a file into an ArrayList we could do it fairly simply with this code:
import java.io.*;
import java.util.*;
...
ArrayList<String> lines = new ArrayList<>();
File dataFile = new File("data.txt");
Scanner data = new Scanner(dataFile);

while (data.hasNextLine()) {
  lines.add(data.nextLine());
}

Subsection 11.2.2 IOException

In earlier chapters we saw that if we wrote code that tried to do something impossible such as accessing an element of an array at an index that didnโ€™t exist or invoking a method on a null reference, Java would through an exception like an ArrayIndexOutOfBoundsException or NullPointerException.
Exceptions are how Java handles situations where a precondition, like we discussed in Sectionย 13.2ย Documentation and invariants is not met causing a bit of code to be unable to satisfiy its postcondition. For instance thereโ€™s an implicit precondition whenever we try to access an array element that the index is valid and if itโ€™s not, thereโ€™s no way for the array access expression to satisfy the postcondition of returning the value at that index.
Creating a Scanner has a precondition that the file represented by the File object actually exists; if it doesnโ€™t thereโ€™s no way to make a Scanner that can read data from it. This can happen for reasons that have nothing to do with bugs in the program. Maybe the user misspelled the file name or accidentally deleted it before they ran the program.
Whatever the reason, if the file does not exist or is otherwise inaccessible, the Scanner constructor will throw a FileNotFoundException. Exceptions are organized into hierarchies and in real-world Java programs there are ways to handle exceptions so they donโ€™t crash our program. FilNotFoundException is one of the exceptions in the IOException hierarchy which represents various things that can go wrong when trying to read and write data.
Unlike ArrayIndexOutOfBoundsException and NullPointerException, IOException is something called a checked exception which means that Java requires us to specify what we will do if one is thrown. There are basically two choices. The simplest is to add throws IOException after the argument list of the method that contains the line creates the Scanner. This is basically passin the buck: the method is saying, this bad thing can happen and I canโ€™t recover if it does so it is now the responsibility of whatever methods call me to deal with it. Those methods can continue to pass the buck by adding throws IOException to their own signatures or eventually some method could handle the exception using a construct weโ€™ll describe below. But within the bounds of the AP curriculum, we should just add throws IOException to any method that needs it.
import java.io.*;
import java.util.*;

public class FileIO {

   // The throws IOException indicates that we are not handling the
   // FileNotFoundException that could be thrown by the Scanner
   // constructor and will just let it crash our program.

   public static void main(String[] args) throws IOException {
      File myFile = new File("data.txt");
      Scanner scan = new Scanner(myFile);
      ...

      scan.close();
   }
}

Activity 11.2.1.

Try the following exercise to practice reading in a file. Notice the compiler error โ€œunreported exception FileNotFoundException; must be caught or declared to be thrownโ€. Add throws IOException to the end of the main method header to fix the error.
Run the code below to see the error message. Add throws and the correct exception to the end of the main method header to fix the error.
Another possibility, which is outside the AP curriculum, is to use a construct called a try/catch block to handle the exception somehow. The right thing to do depends on the context of the program. If the program canโ€™t do anything at all without the file, then the best we can do is maybe print a useful error message and exit. But in some other program it might be possible to ask the user to provide a different file name or to use some default data if the file doesnโ€™t exist.
Here is an example of a try/catch block that catches the FileNotFoundException exception and prints an error message rather than letting the exception crash the program.
The code that may cause an exception goes in the try block, marked by the curly braces after the word try. If the code in the try block throws an exception listed in the parentheses after catch, then the code in the block marked by the curly braces after the catch line will be executed to handle the exception. In this case it prints an error message. Then the code continues after the catch block
try {
    Scanner scan = new Scanner(myFile);
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
}

Subsection 11.2.3 Reading user input with Scanner

Another way to use Scanner that is handy but not part of the AP curriculum, is to read input that the user types. To do that instead of constructing a Scanner with a File object we pass it System.in which is the counterpart to System.out which weโ€™ve been using to print message to the user; System.in is where we can read from the user. When we create a Scanner wrapped around System.in we can then use the Scanner methods to read data the user types.
Hereโ€™s an example of the nextInt method being used to read from the keyboard.

Activity 11.2.2.

The code below will read in the two numbers below it and multiply them. Try changing the input below the code to decimal numbers like 2.5 and run to see the InputMismatchException. Then, change the code to use nextDouble() instead of nextInt() and change the variables to type double to read in decimal numbers.
Notice that the nextInt() and nextDouble() methods read in a number but leave any space or newline characters on the input stream. This can cause problems if we have input to read in multiple lines. Using nextLine and the other Scanner methods together on the same input source sometimes requires code to adjust for the methodsโ€™ different ways of handling whitespace. Java programmers will often add in an extra call to scan.nextLine(); to read in the rest of the line after reading in a number.

Subsection 11.2.4 Read all the lines in a file

A while loop is usually used to read in a file with multiple lines since we donโ€™t know when we open the file how many lines it will contain.
The loop can use the method hasNextLine or hasNext as the loop condition to detect if the file still contains lines to read. A loop with this condition will terminate when there are no more lines to read in the file. After the loop is finished reading the data, the close method from Scanner should be called to close the file.
while (scan.hasNextLine()) {
   String line = scan.nextLine();
   ...
}
scan.close();

Activity 11.2.3.

Complete the code below to count the number of lines in the dictionary file using a while loop and then print how many lines are in the file.

Subsection 11.2.5 Loading file data

We can save a file line by line into a data structure such as an array or an ArrayList. In the SpellChecker class in Sectionย 6.2ย Looping over arrays, code was provided that read all the words into a array. But now that we know about ArrayLists, thatโ€™s a better data structure to use since we donโ€™t need to know how many lines the file contains in order to build up an ArrayList they way we would with an array.
The following exercise reads in a data file about Pokemon and prints out the first ten lines in the file. This file has the extension csv which stands for Comma Separated Values. All spreadsheets can be saved as CSV text files, and spreadsheet software can easily open CSV files as spreadsheets. You can take a look at the pokemon.csv file contents below:
Data: pokemon.csv
Number,Pokemon,Type 1,Type 2,HP,Attack,Defense,Speed,PNG,Description
1,Bulbasaur,Grass,Poison,45,49,49,45,https://play.pokemonshowdown.com/sprites/bw/bulbasaur.png,A strange seed was planted on its back at birth. The plant sprouts and grows with this Pokemon.
2,Ivysaur,Grass,Poison,60,62,63,60,https://play.pokemonshowdown.com/sprites/bw/ivysaur.png,Often seen swimming elegantly by lake shores. It is often mistaken for the Japanese monster Kappa.
3,Venusaur,Grass,Poison,80,82,83,80,https://play.pokemonshowdown.com/sprites/bw/venusaur.png,Because it stores several kinds of toxic gases in its body it is prone to exploding without warning.
4,Charmander,Fire,,39,52,43,65,https://play.pokemonshowdown.com/sprites/bw/charmander.png,Obviously prefers hot places. When it rains steam is said to spout from the tip of its tail.
5,Charmeleon,Fire,,58,64,58,80,https://play.pokemonshowdown.com/sprites/bw/charmeleon.png,When it swings its burning tail it elevates the temperature to unbearably high levels.
6,Charizard,Fire,Flying,78,84,78,100,https://play.pokemonshowdown.com/sprites/bw/charizard.png,Spits fire that is hot enough to melt boulders. Known to cause forest fires unintentionally.
7,Squirtle,Water,,44,48,65,43,https://play.pokemonshowdown.com/sprites/bw/squirtle.png,After birth its back swells and hardens into a shell. Powerfully sprays foam from its mouth.
8,Wartortle,Water,,59,63,80,58,https://play.pokemonshowdown.com/sprites/bw/wartortle.png,Often hides in water to stalk unwary prey. For swimming fast it moves its ears to maintain balance.
9,Blastoise,Water,,79,83,100,78,https://play.pokemonshowdown.com/sprites/bw/blastoise.png,A brutal Pokemon with pressurized water jets on its shell. They are used for high speed tackles.
10,Caterpie,Bug,,45,30,35,45,https://play.pokemonshowdown.com/sprites/bw/caterpie.png,Its short feet are tipped with suction pads that enable it to tirelessly climb slopes and walls.
11,Metapod,Bug,,50,20,55,30,https://play.pokemonshowdown.com/sprites/bw/metapod.png,This Pokemon is vulnerable to attack while its shell is soft exposing its weak and tender body.
12,Butterfree,Bug,Flying,60,45,50,70,https://play.pokemonshowdown.com/sprites/bw/butterfree.png,In battle it flaps its wings at high speed to release highly toxic dust into the air.
13,Weedle,Bug,Poison,40,35,30,50,https://play.pokemonshowdown.com/sprites/bw/weedle.png,Often found in forests eating leaves. It has a sharp venomous stinger on its head.
14,Kakuna,Bug,Poison,45,25,50,35,https://play.pokemonshowdown.com/sprites/bw/kakuna.png,Almost incapable of moving this Pokemon can only harden its shell to protect itself from predators.
15,Beedrill,Bug,Poison,65,80,40,75,https://play.pokemonshowdown.com/sprites/bw/beedrill.png,Flies at high speed and attacks using its large venomous stingers on its forelegs and tail.
16,Pidgey,Normal,Flying,40,45,40,56,https://play.pokemonshowdown.com/sprites/bw/pidgey.png,A common sight in forests and woods. It flaps its wings at ground level to kick up blinding sand.
17,Pidgeotto,Normal,Flying,63,60,55,71,https://play.pokemonshowdown.com/sprites/bw/pidgeotto.png,Very protective of its sprawling territorial area this Pokemon will fiercely peck at any intruder.
18,Pidgeot,Normal,Flying,83,80,75,91,https://play.pokemonshowdown.com/sprites/bw/pidgeot.png,When hunting it skims the surface of water at high speed to pick off unwary prey such as MAGIKARP.
19,Rattata,Normal,,30,56,35,72,https://play.pokemonshowdown.com/sprites/bw/rattata.png,Bites anything when it attacks. Small and very quick it is a common sight in many places.
20,Raticate,Normal,,55,81,60,97,https://play.pokemonshowdown.com/sprites/bw/raticate.png,It uses its whiskers to maintain its balance. It apparently slows down if they are cut off.
21,Spearow,Normal,Flying,40,60,30,70,https://play.pokemonshowdown.com/sprites/bw/spearow.png,Eats bugs in grassy areas. It has to flap its short wings at high speed to stay airborne.
22,Fearow,Normal,Flying,65,90,65,100,https://play.pokemonshowdown.com/sprites/bw/fearow.png,With its huge and magnificent wings it can keep aloft without ever having to land for rest.
23,Ekans,Poison,,35,60,44,55,https://play.pokemonshowdown.com/sprites/bw/ekans.png,Moves silently and stealthily. Eats the eggs of birds such as PIDGEY and SPEAROW whole.
24,Arbok,Poison,,60,85,69,80,https://play.pokemonshowdown.com/sprites/bw/arbok.png,It is rumored that the ferocious warning markings on its belly differ from area to area.
25,Pikachu,Electric,,35,55,30,90,https://play.pokemonshowdown.com/sprites/bw/pikachu.png,When several of these Pokemon gather their electricity could build and cause lightning storms.
26,Raichu,Electric,,60,90,55,100,https://play.pokemonshowdown.com/sprites/bw/raichu.png,Its long tail serves as a ground to protect itself from its own high voltage power.
27,Sandshrew,Ground,,50,75,85,40,https://play.pokemonshowdown.com/sprites/bw/sandshrew.png,Burrows deep underground in arid locations far from water. It only emerges to hunt for food.
28,Sandslash,Ground,,75,100,110,65,https://play.pokemonshowdown.com/sprites/bw/sandslash.png,Curls up into a spiny ball when threatened. It can roll while curled up to attack or escape.
29,NidoranF,Poison,,55,47,52,41,https://play.pokemonshowdown.com/sprites/bw/nidoranf.png,Although small its venomous barbs render this Pokemon dangerous. The female has smaller horns.
30,Nidorina,Poison,,70,62,67,56,https://play.pokemonshowdown.com/sprites/bw/nidorina.png,The female's horn develops slowly. Prefers physical attacks such as clawing and biting.
31,Nidoqueen,Poison,Ground,90,82,87,76,https://play.pokemonshowdown.com/sprites/bw/nidoqueen.png,Its hard scales provide strong protection. It uses its hefty bulk to execute powerful moves.
32,NidoranM,Poison,,46,57,40,50,https://play.pokemonshowdown.com/sprites/bw/nidoranm.png,Stiffens its ears to sense danger. The larger its horns the more powerful its secreted venom.
33,Nidorino,Poison,,61,72,57,65,https://play.pokemonshowdown.com/sprites/bw/nidorino.png,An aggressive Pokemon that is quick to attack. The horn on its head secretes a powerful venom.
34,Nidoking,Poison,Ground,81,92,77,85,https://play.pokemonshowdown.com/sprites/bw/nidoking.png,It uses its powerful tail in battle to smash constrict then break the prey's bones.
35,Clefairy,Normal,,70,45,48,35,https://play.pokemonshowdown.com/sprites/bw/clefairy.png,Its magical and cute appeal has many admirers. It is rare and found only in certain areas.
36,Clefable,Normal,,95,70,73,60,https://play.pokemonshowdown.com/sprites/bw/clefable.png,A timid fairy Pokemon that is rarely seen. It will run and hide the moment it senses people.
37,Vulpix,Fire,,38,41,40,65,https://play.pokemonshowdown.com/sprites/bw/vulpix.png,At the time of birth it has just one tail. The tail splits from its tip as it grows older.
38,Ninetales,Fire,,73,76,75,100,https://play.pokemonshowdown.com/sprites/bw/ninetales.png,Very smart and very vengeful. Grabbing one of its many tails could result in a 1000-year curse.
39,Jigglypuff,Normal,,115,45,20,20,https://play.pokemonshowdown.com/sprites/bw/jigglypuff.png,When its huge eyes light up it sings a mysteriously soothing melody that lulls its enemies to sleep.
40,Wigglytuff,Normal,,140,70,45,45,https://play.pokemonshowdown.com/sprites/bw/wigglytuff.png,The body is soft and rubbery. When angered it will suck in air and inflate itself to an enormous size.
41,Zubat,Poison,Flying,40,45,35,55,https://play.pokemonshowdown.com/sprites/bw/zubat.png,Forms colonies in perpetually dark places. Uses ultrasonic waves to identify and approach targets.
42,Golbat,Poison,Flying,75,80,70,90,https://play.pokemonshowdown.com/sprites/bw/golbat.png,Once it strikes it will not stop draining energy from the victim even if it gets too heavy to fly.
43,Oddish,Grass,Poison,45,50,55,30,https://play.pokemonshowdown.com/sprites/bw/oddish.png,During the day it keeps its face buried in the ground. At night it wanders around sowing its seeds.
44,Gloom,Grass,Poison,60,65,70,40,https://play.pokemonshowdown.com/sprites/bw/gloom.png,The fluid that oozes from its mouth isn't drool. It is a nectar that is used to attract prey.
45,Vileplume,Grass,Poison,75,80,85,50,https://play.pokemonshowdown.com/sprites/bw/vileplume.png,The larger its petals the more toxic pollen it contains. Its big head is heavy and hard to hold up.
46,Paras,Bug,Grass,35,70,55,25,https://play.pokemonshowdown.com/sprites/bw/paras.png,Burrows to suck tree roots. The mushrooms on its back grow by drawing nutrients from the bug host.
47,Parasect,Bug,Grass,60,95,80,30,https://play.pokemonshowdown.com/sprites/bw/parasect.png,A host-parasite pair in which the parasite mushroom has taken over the host bug. Prefers damp places.
48,Venonat,Bug,Poison,60,55,50,45,https://play.pokemonshowdown.com/sprites/bw/venonat.png,Lives in the shadows of tall trees where it eats insects. It is attracted by light at night.
49,Venomoth,Bug,Poison,70,65,60,90,https://play.pokemonshowdown.com/sprites/bw/venomoth.png,The dust-like scales covering its wings are color coded to indicate the kinds of poison it has.
50,Diglett,Ground,,10,55,25,95,https://play.pokemonshowdown.com/sprites/bw/diglett.png,Lives about one yard underground where it feeds on plant roots. It sometimes appears above ground.
51,Dugtrio,Ground,,35,80,50,120,https://play.pokemonshowdown.com/sprites/bw/dugtrio.png,A team of DIGLETT triplets. It triggers huge earthquakes by burrowing 60 miles underground.
52,Meowth,Normal,,40,45,35,90,https://play.pokemonshowdown.com/sprites/bw/meowth.png,Adores circular objects. Wanders the streets on a nightly basis to look for dropped loose change.
53,Persian,Normal,,65,70,60,115,https://play.pokemonshowdown.com/sprites/bw/persian.png,Although its fur has many admirers it is tough to raise as a pet because of its fickle meanness.
54,Psyduck,Water,,50,52,48,55,https://play.pokemonshowdown.com/sprites/bw/psyduck.png,While lulling its enemies with its vacant look this wily Pokemon will use psychokinetic powers.
55,Golduck,Water,,80,82,78,85,https://play.pokemonshowdown.com/sprites/bw/golduck.png,Often seen swimming elegantly by lake shores. It is often mistaken for the Japanese monster Kappa.
56,Mankey,Fighting,,40,80,35,70,https://play.pokemonshowdown.com/sprites/bw/mankey.png,Extremely quick to anger. It could be docile one moment then thrashing away the next instant.
57,Primeape,Fighting,,65,105,60,95,https://play.pokemonshowdown.com/sprites/bw/primeape.png,Always furious and tenacious to boot. It will not abandon chasing its quarry until it is caught.
58,Growlithe,Fire,,55,70,45,60,https://play.pokemonshowdown.com/sprites/bw/growlithe.png,Very protective of its territory. It will bark and bite to repel intruders from its space.
59,Arcanine,Fire,,90,110,80,95,https://play.pokemonshowdown.com/sprites/bw/arcanine.png,A Pokemon that has been admired since the past for its beauty. It runs agilely as if on wings.
60,Poliwag,Water,,40,50,40,90,https://play.pokemonshowdown.com/sprites/bw/poliwag.png,Its newly grown legs prevent it from running. It appears to prefer swimming than trying to stand.
61,Poliwhirl,Water,,65,65,65,90,https://play.pokemonshowdown.com/sprites/bw/poliwhirl.png,Capable of living in or out of water. When out of water it sweats to keep its body slimy.
62,Poliwrath,Water,Fighting,90,85,95,70,https://play.pokemonshowdown.com/sprites/bw/poliwrath.png,An adept swimmer at both the front crawl and breast stroke. Easily overtakes the best human swimmers.
63,Abra,Psychic,,25,20,15,90,https://play.pokemonshowdown.com/sprites/bw/abra.png,Using its ability to read minds it will identify impending danger and TELEPORT to safety.
64,Kadabra,Psychic,,40,35,30,105,https://play.pokemonshowdown.com/sprites/bw/kadabra.png,It emits special alpha waves from its body that induce headaches just by being close by.
65,Alakazam,Psychic,,55,50,45,120,https://play.pokemonshowdown.com/sprites/bw/alakazam.png,Its brain can outperform a supercomputer. Its intelligence quotient is said to be 5000.
66,Machop,Fighting,,70,80,50,35,https://play.pokemonshowdown.com/sprites/bw/machop.png,Loves to build its muscles. It trains in all styles of martial arts to become even stronger.
67,Machoke,Fighting,,80,100,70,45,https://play.pokemonshowdown.com/sprites/bw/machoke.png,Its muscular body is so powerful it must wear a power save belt to be able to regulate its motions.
68,Machamp,Fighting,,90,130,80,55,https://play.pokemonshowdown.com/sprites/bw/machamp.png,Using its heavy muscles it throws powerful punches that can send the victim clear over the horizon.
69,Bellsprout,Grass,Poison,50,75,35,40,https://play.pokemonshowdown.com/sprites/bw/bellsprout.png,A carnivorous Pokemon that traps and eats bugs. It uses its root feet to soak up needed moisture.
70,Weepinbell,Grass,Poison,65,90,50,55,https://play.pokemonshowdown.com/sprites/bw/weepinbell.png,It spits out POISONPOWDER to immobilize the enemy and then finishes it with a spray of ACID.
71,Victreebel,Grass,Poison,80,105,65,70,https://play.pokemonshowdown.com/sprites/bw/victreebel.png,Said to live in huge colonies deep in jungles although no one has ever returned from there.
72,Tentacool,Water,Poison,40,40,35,70,https://play.pokemonshowdown.com/sprites/bw/tentacool.png,Drifts in shallow seas. Anglers who hook them by accident are often punished by its stinging acid.
73,Tentacruel,Water,Poison,80,70,65,100,https://play.pokemonshowdown.com/sprites/bw/tentacruel.png,The tentacles are normally kept short. On hunts they are extended to ensnare and immobilize prey.
74,Geodude,Rock,Ground,40,80,100,20,https://play.pokemonshowdown.com/sprites/bw/geodude.png,Found in fields and mountains. Mistaking them for boulders people often step or trip on them.
75,Graveler,Rock,Ground,55,95,115,35,https://play.pokemonshowdown.com/sprites/bw/graveler.png,Rolls down slopes to move. It rolls over any obstacle without slowing or changing its direction.
76,Golem,Rock,Ground,80,110,130,45,https://play.pokemonshowdown.com/sprites/bw/golem.png,Its boulder-like body is extremely hard. It can easily withstand dynamite blasts without damage.
77,Ponyta,Fire,,50,85,55,90,https://play.pokemonshowdown.com/sprites/bw/ponyta.png,Its hooves are 10 times harder than diamonds. It can trample anything completely flat in little time.
78,Rapidash,Fire,,65,100,70,105,https://play.pokemonshowdown.com/sprites/bw/rapidash.png,Very competitive this Pokemon will chase anything that moves fast in the hopes of racing it.
79,Slowpoke,Water,Psychic,90,65,65,15,https://play.pokemonshowdown.com/sprites/bw/slowpoke.png,Incredibly slow and dopey. It takes 5 seconds for it to feel pain when under attack.
80,Slowbro,Water,Psychic,95,75,110,30,https://play.pokemonshowdown.com/sprites/bw/slowbro.png,The SHELLDER that is latched onto SLOWPOKE's tail is said to feed on the host's left over scraps.
81,Magnemite,Electric,,25,35,70,45,https://play.pokemonshowdown.com/sprites/bw/magnemite.png,Uses anti-gravity to stay suspended. Appears without warning and uses THUNDER WAVE and similar moves.
82,Magneton,Electric,,50,60,95,70,https://play.pokemonshowdown.com/sprites/bw/magneton.png,Formed by several MAGNEMITEs linked together. They frequently appear when sunspots flare up.
83,Farfetch'd,Normal,Flying,52,65,55,60,https://play.pokemonshowdown.com/sprites/bw/farfetchd.png,The sprig of green onions it holds is its weapon. It is used much like a metal sword.
84,Doduo,Normal,Flying,35,85,45,75,https://play.pokemonshowdown.com/sprites/bw/doduo.png,A bird that makes up for its poor flying with its fast foot speed. Leaves giant footprints.
85,Dodrio,Normal,Flying,60,110,70,100,https://play.pokemonshowdown.com/sprites/bw/dodrio.png,Uses its three brains to execute complex plans. While two heads sleep one head stays awake.
86,Seel,Water,,65,45,55,45,https://play.pokemonshowdown.com/sprites/bw/seel.png,The protruding horn on its head is very hard. It is used for bashing through thick ice.
87,Dewgong,Water,Ice,90,70,80,70,https://play.pokemonshowdown.com/sprites/bw/dewgong.png,Stores thermal energy in its body. Swims at a steady 8 knots even in intensely cold waters.
88,Grimer,Poison,,80,80,50,25,https://play.pokemonshowdown.com/sprites/bw/grimer.png,Appears in filthy areas. Thrives by sucking up polluted sludge that is pumped out of factories.
89,Muk,Poison,,105,105,75,50,https://play.pokemonshowdown.com/sprites/bw/muk.png,Thickly covered with a filthy vile sludge. It is so toxic even its footprints contain poison.
90,Shellder,Water,,30,65,100,40,https://play.pokemonshowdown.com/sprites/bw/shellder.png,Its hard shell repels any kind of attack. It is vulnerable only when its shell is open.
91,Cloyster,Water,Ice,50,95,180,70,https://play.pokemonshowdown.com/sprites/bw/cloyster.png,When attacked it launches its horns in quick volleys. Its innards have never been seen.
92,Gastly,Ghost,Poison,30,35,30,80,https://play.pokemonshowdown.com/sprites/bw/gastly.png,Almost invisible this gaseous Pokemon cloaks the target and puts it to sleep without notice.
93,Haunter,Ghost,Poison,45,50,45,95,https://play.pokemonshowdown.com/sprites/bw/haunter.png,Because of its ability to slip through block walls it is said to be from another dimension.
94,Gengar,Ghost,Poison,60,65,60,110,https://play.pokemonshowdown.com/sprites/bw/gengar.png,Under a full moon this Pokemon likes to mimic the shadows of people and laugh at their fright.
95,Onix,Rock,Ground,35,45,160,70,https://play.pokemonshowdown.com/sprites/bw/onix.png,As it grows the stone portions of its body harden to become similar to a diamond but colored black.
96,Drowzee,Psychic,,60,48,45,42,https://play.pokemonshowdown.com/sprites/bw/drowzee.png,Puts enemies to sleep then eats their dreams. Occasionally gets sick from eating bad dreams.
97,Hypno,Psychic,,85,73,70,67,https://play.pokemonshowdown.com/sprites/bw/hypno.png,When it locks eyes with an enemy it will use a mix of PSI moves such as HYPNOSIS and CONFUSION.
98,Krabby,Water,,30,105,90,50,https://play.pokemonshowdown.com/sprites/bw/krabby.png,Its pincers are not only powerful weapons they are used for balance when walking sideways.
99,Kingler,Water,,55,130,115,75,https://play.pokemonshowdown.com/sprites/bw/kingler.png,The large pincer has 10000 hp of crushing power. However its huge size makes it unwieldy to use.
100,Voltorb,Electric,,40,30,50,100,https://play.pokemonshowdown.com/sprites/bw/voltorb.png,Usually found in power plants. Easily mistaken for a Pokeball they have zapped many people.
101,Electrode,Electric,,60,50,70,140,https://play.pokemonshowdown.com/sprites/bw/electrode.png,It stores electric energy under very high pressure. It often explodes with little or no provocation.
102,Exeggcute,Grass,Psychic,60,40,80,40,https://play.pokemonshowdown.com/sprites/bw/exeggcute.png,Often mistaken for eggs. When disturbed they quickly gather and attack in swarms.
103,Exeggutor,Grass,Psychic,95,95,85,55,https://play.pokemonshowdown.com/sprites/bw/exeggutor.png,Legend has it that on rare occasions one of its heads will drop off and continue on as an EXEGGCUTE.
104,Cubone,Ground,,50,50,95,35,https://play.pokemonshowdown.com/sprites/bw/cubone.png,Because it never removes its skull helmet no one has ever seen this Pokemon's real face.
105,Marowak,Ground,,60,80,110,45,https://play.pokemonshowdown.com/sprites/bw/marowak.png,The bone it holds is its key weapon. It throws the bone skillfully like a boomerang to KO targets.
106,Hitmonlee,Fighting,,50,120,53,87,https://play.pokemonshowdown.com/sprites/bw/hitmonlee.png,When in a hurry its legs lengthen progressively. It runs smoothly with extra long loping strides.
107,Hitmonchan,Fighting,,50,105,79,76,https://play.pokemonshowdown.com/sprites/bw/hitmonchan.png,While apparently doing nothing it fires punches in lightning fast volleys that are impossible to see.
108,Lickitung,Normal,,90,55,75,30,https://play.pokemonshowdown.com/sprites/bw/lickitung.png,Its tongue can be extended like a chameleon's. It leaves a tingling sensation when it licks enemies.
109,Koffing,Poison,,40,65,95,35,https://play.pokemonshowdown.com/sprites/bw/koffing.png,Because it stores several kinds of toxic gases in its body it is prone to exploding without warning.
110,Weezing,Poison,,65,90,120,60,https://play.pokemonshowdown.com/sprites/bw/weezing.png,Where two kinds of poison gases meet 2 KOFFINGs can fuse into a WEEZING over many years.
111,Rhyhorn,Ground,Rock,80,85,95,25,https://play.pokemonshowdown.com/sprites/bw/rhyhorn.png,Its massive bones are 1000 times harder than human bones. It can easily knock a trailer flying.
112,Rhydon,Ground,Rock,105,130,120,40,https://play.pokemonshowdown.com/sprites/bw/rhydon.png,Protected by an armor-like hide it is capable of living in molten lava of 3600 degrees.
113,Chansey,Normal,,250,5,5,50,https://play.pokemonshowdown.com/sprites/bw/chansey.png,A rare and elusive Pokemon that is said to bring happiness to those who manage to get it.
114,Tangela,Grass,,65,55,115,60,https://play.pokemonshowdown.com/sprites/bw/tangela.png,The whole body is swathed with wide vines that are similar to seaweed. Its vines shake as it walks.
115,Kangaskhan,Normal,,105,95,80,90,https://play.pokemonshowdown.com/sprites/bw/kangaskhan.png,The infant rarely ventures out of its mother's protective pouch until it is 3 years old.
116,Horsea,Water,,30,40,70,60,https://play.pokemonshowdown.com/sprites/bw/horsea.png,Known to shoot down flying bugs with precision blasts of ink from the surface of the water.
117,Seadra,Water,,55,65,95,85,https://play.pokemonshowdown.com/sprites/bw/seadra.png,Capable of swimming backwards by rapidly flapping its wing-like pectoral fins and stout tail.
118,Goldeen,Water,,45,67,60,63,https://play.pokemonshowdown.com/sprites/bw/goldeen.png,Its tail fin billows like an elegant ballroom dress giving it the nickname of the Water Queen.
119,Seaking,Water,,80,92,65,68,https://play.pokemonshowdown.com/sprites/bw/seaking.png,In the autumn spawning season they can be seen swimming powerfully up rivers and creeks.
120,Staryu,Water,,30,45,55,85,https://play.pokemonshowdown.com/sprites/bw/staryu.png,An enigmatic Pokemon that can effortlessly regenerate any appendage it loses in battle.
121,Starmie,Water,Psychic,60,75,85,115,https://play.pokemonshowdown.com/sprites/bw/starmie.png,Its central core glows with the seven colors of the rainbow. Some people value the core as a gem.
122,Mr. Mime,Psychic,,40,45,65,90,https://play.pokemonshowdown.com/sprites/bw/mrmime.png,If interrupted while it is miming it will slap around the offender with its broad hands.
123,Scyther,Bug,Flying,70,110,80,105,https://play.pokemonshowdown.com/sprites/bw/scyther.png,With ninja-like agility and speed it can create the illusion that there is more than one.
124,Jynx,Ice,Psychic,65,50,35,95,https://play.pokemonshowdown.com/sprites/bw/jynx.png,It seductively wiggles its hips as it walks. It can cause people to dance in unison with it.
125,Electabuzz,Electric,,65,83,57,105,https://play.pokemonshowdown.com/sprites/bw/electabuzz.png,Normally found near power plants they can wander away and cause major blackouts in cities.
126,Magmar,Fire,,65,95,57,93,https://play.pokemonshowdown.com/sprites/bw/magmar.png,Its body always burns with an orange glow that enables it to hide perfectly among flames.
127,Pinsir,Bug,,65,125,100,85,https://play.pokemonshowdown.com/sprites/bw/pinsir.png,If it fails to crush the victim in its pincers it will swing it around and toss it hard.
128,Tauros,Normal,,75,100,95,110,https://play.pokemonshowdown.com/sprites/bw/tauros.png,When it targets an enemy it charges furiously while whipping its body with its long tails.
129,Magikarp,Water,,20,10,55,80,https://play.pokemonshowdown.com/sprites/bw/magikarp.png,In the distant past it was somewhat stronger than the horribly weak descendants that exist today.
130,Gyarados,Water,Flying,95,125,79,81,https://play.pokemonshowdown.com/sprites/bw/gyarados.png,Rarely seen in the wild. Huge and vicious it is capable of destroying entire cities in a rage.
131,Lapras,Water,Ice,130,85,80,60,https://play.pokemonshowdown.com/sprites/bw/lapras.png,A Pokemon that has been overhunted almost to extinction. It can ferry people across the water.
132,Ditto,Normal,,48,48,48,48,https://play.pokemonshowdown.com/sprites/bw/ditto.png,Capable of copying an enemy's genetic code to instantly transform itself into a duplicate of the enemy.
133,Eevee,Normal,,55,55,50,55,https://play.pokemonshowdown.com/sprites/bw/eevee.png,Its genetic code is irregular. It may mutate if it is exposed to radiation from element STONEs.
134,Vaporeon,Water,,130,65,60,65,https://play.pokemonshowdown.com/sprites/bw/vaporeon.png,Lives close to water. Its long tail is ridged with a fin which is often mistaken for a mermaid's.
135,Jolteon,Electric,,65,65,60,130,https://play.pokemonshowdown.com/sprites/bw/jolteon.png,It accumulates negative ions in the atmosphere to blast out 10000- volt lightning bolts.
136,Flareon,Fire,,65,130,60,65,https://play.pokemonshowdown.com/sprites/bw/flareon.png,When storing thermal energy in its body its temperature could soar to over 1600 degrees.
137,Porygon,Normal,,65,60,70,40,https://play.pokemonshowdown.com/sprites/bw/porygon.png,A Pokemon that consists entirely of programming code. Capable of moving freely in cyberspace.
138,Omanyte,Rock,Water,35,40,100,35,https://play.pokemonshowdown.com/sprites/bw/omanyte.png,Although long extinct in rare cases it can be genetically resurrected from fossils.
139,Omastar,Rock,Water,70,60,125,55,https://play.pokemonshowdown.com/sprites/bw/omastar.png,A prehistoric Pokemon that died out when its heavy shell made it impossible to catch prey.
140,Kabuto,Rock,Water,30,80,90,55,https://play.pokemonshowdown.com/sprites/bw/kabuto.png,A Pokemon that was resurrected from a fossil found in what was once the ocean floor eons ago.
141,Kabutops,Rock,Water,60,115,105,80,https://play.pokemonshowdown.com/sprites/bw/kabutops.png,Its sleek shape is perfect for swimming. It slashes prey with its claws and drains the body fluids.
142,Aerodactyl,Rock,Flying,80,105,65,130,https://play.pokemonshowdown.com/sprites/bw/aerodactyl.png,A ferocious prehistoric Pokemon that goes for the enemy's throat with its serrated saw-like fangs.
143,Snorlax,Normal,,160,110,65,30,https://play.pokemonshowdown.com/sprites/bw/snorlax.png,Very lazy. Just eats and sleeps. As its rotund bulk builds it becomes steadily more slothful.
144,Articuno,Ice,Flying,90,85,100,85,https://play.pokemonshowdown.com/sprites/bw/articuno.png,A legendary bird Pokemon that is said to appear to doomed people who are lost in icy mountains.
145,Zapdos,Electric,Flying,90,90,85,100,https://play.pokemonshowdown.com/sprites/bw/zapdos.png,A legendary bird Pokemon that is said to appear from clouds while dropping enormous lightning bolts.
146,Moltres,Fire,Flying,90,100,90,90,https://play.pokemonshowdown.com/sprites/bw/moltres.png,Known as the legendary bird of fire. Every flap of its wings creates a dazzling flash of flames.
147,Dratini,Dragon,,41,64,45,50,https://play.pokemonshowdown.com/sprites/bw/dratini.png,Long considered a mythical Pokemon until recently when a small colony was found living underwater.
148,Dragonair,Dragon,,61,84,65,70,https://play.pokemonshowdown.com/sprites/bw/dragonair.png,A mystical Pokemon that exudes a gentle aura. Has the ability to change climate conditions.
149,Dragonite,Dragon,Flying,91,134,95,80,https://play.pokemonshowdown.com/sprites/bw/dragonite.png,An extremely rarely seen marine Pokemon. Its intelligence is said to match that of humans.
150,Mewtwo,Psychic,,106,110,90,130,https://play.pokemonshowdown.com/sprites/bw/mewtwo.png,It was created by a scientist after years of horrific gene splicing and DNA engineering experiments.
151,Mew,Psychic,,100,100,100,100,https://play.pokemonshowdown.com/sprites/bw/mew.png,So rare that it is still said to be a mirage by many experts. Only a few people have seen it worldwide.

Activity 11.2.4.

Complete the code in the main method below to read in the first ten lines of the pokemon file using the Scanner class, printing each line and save to the pokemonLines ArrayList.

Subsection 11.2.6 Reading files with java.nio.file

Although not covered in the AP curriculum, the more modern way (by which we mean, it has only been around for fourteen years) to read all the lines from a file is using the classes java.nio.file package. The nio stands for โ€œnew input/outputโ€ and was added in Java version 7. The two important classes for our purposes in this package are Files (note the plural) and Path.
Path serves basically the same purpose as java.io.File, giving us a way to refer to file on the computerโ€™s hard drive. And Files contains a number of utility methods for interacting with files.
The one we care about is readAllLines which takes a Path as its argument and returns a List of String values, one String per line. List is an interface, another feature of Java thatโ€™s not part of the AP curriculum but which are a key part of real Java programming. For now all we need to know is that a List is effectively the same as an ArrayList.
Like the Scanner constructor, readAllLines method throws an IOException if the file cannot be read.
The Path equivalent of new File("filename.txt") is Path.of("filename.txt") so after importing java.nio.file.* we can get all the lines in a file using one line:
List<String> lines = Files.readAllLines(Path.of("data.txt"));
Under the covers readAllLines is almost certainly using an ArrayList which is a kind of List. The advantage of storing the lines in a dynamic data structure like an ArrayList, instead of an array, is that we do not need to know how many lines we are going to read when you create the ArrayList the way ve do when we create an array. The ArrayList can then grow in size as needed. (If we absolutely need an array, we can convert the List to an array declared to be the correct size with the toArray method on List:
String[] array = list.toArray(new String[0]);
The empty array passed as an argument to toArray tells Java what kind of array to make; it then allocates a new array of the approprite size to hold all the elements of the list.

Activity 11.2.5.

Complete the code in the main method below to reads all lines of the file using Files.readAllLines into a List<String> named lines. Add a loop that prints out the first 10 pokemon.
You have attempted of activities on this page.