Skip to main content
Logo image

Section 11.1 Files

A file contains data that persists when the program is not running. Files are stored on our computers’ hard drives, have names, and are organized into hierarchical folders. Our programs can open files and read the data they contain into memory. For example in Section 6.2 Looping over arrays, we created a SpellChecker class that reads a dictionary file into an array of words which the spellcheck method could use to verify if a word is spelled correctly.
By separating the data the program needs (the dictionary) from the program itself, we can use the same program with different data. For example, we could use our spellchecker to spellcheck a different language if we ran it with a file contain a list of words in that language.
In this lesson, we will learn how to read data from a file in Java.

Subsection 11.1.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 classes which are part of the AP curriculum. Then we’ll look at a more modern and convenient set of classes that you might want to use in real programs.
On order to work with files, the first thing we need is an object to represent a file. 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 constructor 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");
The File object just gives us a way to refer to the file. To read data from the file 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. (We previously used Scanner in Subsection 2.2.5 Input to read input typed by the user.)
import java.io.*;
import java.util.*;
...
File dataFile = new File("data.txt");
Scanner data = new Scanner(dataFile);
Once we construct a Scanner, we can use it to repeatedly 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 either the next newline character or the end of the file. It returns the line 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 and 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 a 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 to 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.*;
...
File dataFile = new File("data.txt");
Scanner data = new Scanner(dataFile);
ArrayList<String> lines = new ArrayList<>();

while (data.hasNextLine()) {
  lines.add(data.nextLine());
}
// Now lines contains all the lines from data.txt

Subsection 11.1.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 throw an exception like an ArrayIndexOutOfBoundsException or NullPointerException.
Exceptions are how Java handles situations where a bit of code just can’t do what it’s supposed to do. For instance if we try to access an array element that doesn’t exist, there’s no good way to continue—the program was expecting a value and there’s no value to be had. Which is why Java throws an ArrayIndexOutOfBoundsException in that case.
To create a Scanner to read from a file, the file has to actually exist—if it doesn’t, there’s obviously no way to read data from it. It doesn’t really matter why the file doesn’t exist and it’s not necessarily due to to a bug in the program. Maybe the user provided the wrong file name or maybe they deleted the file 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 which is a kind of IOException. (In real-world Java programs there are ways to handle exceptions so they don’t crash our program and exceptions are organized into hierarchies so programs can choose to handle different kinds of exceptions differently. The different kinds of IOException represent all the things that can go wrong when trying to read and write data. Not finding a needed file is just one of those things.)

Subsection 11.1.3 Throwing exceptions

Unlike ArrayIndexOutOfBoundsException and NullPointerException, an IOException is a checked exception which means that Java requires us to specify what our code will do if one is thrown.
There are basically two choices. Our code can also throw the exception or we can handle it. However the second option is not part of the AP curriculum so for now the simplest thing to do is to have our code also throw the exception which we achieve by simply adding throws IOException clause to the signature of the method that constructs the Scanner.
The throws clause goes after the argument list. By adding a throws clause we are passing the buck, declaring that this this bad thing can happen in the method and the method can’t recover if it does, so it is now the responsibility of whatever other methods call it 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. Here’s how we could add it to a main method.
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.1.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.

Subsection 11.1.4 Catching exceptions

The other way to deal with exceptions, which is outside the AP curriculum, is to use a construct called a try/catch block to handle the exception somehow. It looks like this
try {
    Scanner scan = new Scanner(myFile);
    // Do stuff with the Scanner here. If the constructor throws an
    // exception we will never get here and thus won't try to use scan.
} catch (IOException e) {
    System.out.println("File not found!");
}
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 of a type 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. The code then continues after the catch block.
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 as show above. 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.

Subsection 11.1.5 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. (It’s a good idea to close the Scanner when we’re done with it because there is a limit on the number of files a program can have open at once. But note that once we close a Scanner we can no longer read from it.)
while (scan.hasNextLine()) {
   String line = scan.nextLine();
   ...
}
scan.close();

Activity 11.1.2.

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.1.6 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 that code required us to hard-code the size of the array to match the number of lines in our dictionary file. If we added or removed words from the dictionary we’d have to change our code to fix the size of the array. (Or we could write code like the previous example to count the number of lines in the file and then make the array and then load the lines into it but that would require reading through the file twice.)
ArrayLists, are a much better data structure to use to collect lines from a file 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 Pokémon 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. For now we’ll just read the lines of the file into an ArrayList; in the next section we’ll look at how to break each line up into individual pieces of data about specific Pokémon.
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.1.3.

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 lines ArrayList.

Subsection 11.1.7 Reading files with java.nio.file

Although not covered in the AP curriculum, the more modern way to read all the lines from a file (and by modern we mean it was added to Java in 2011) 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. Which we can deal with the same way as before, most likely by declaring that our method also throws IOException.
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 we 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 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 appropriate size to hold all the elements of the list.

Activity 11.1.4.

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 can use the same methods with List as with ArrayList.
You have attempted of activities on this page.