Skip to main content
Engineering LibreTexts

4.5: From the Java Library- java.io.File and file input (Optional)

  • Page ID
    15081
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    [pg-sec-fileclass]

    In addition to command-line and GUI user interfaces, there is one more standard user interface, files. In this section we show how the Scanner class, that was used in Chapter 2 for keyboard input, can also read input from files. Reading input from a file is relevant to only certain types of programming problems. It is hard to imagine how a file would be used in playing the One Row Nim game but a file might very well be useful to store a collection of riddles that could be read and displayed by a Java program. We will develop such a program later in this section.

    Java has two types of files, text files and binary files. A text file stores a sequence of characters and is the type of file created by standard text editors like NotePad and WordPad on a Windows computer or SimpleText on a Macintosh. A binary file has a more general format that can store numbers and other data the way they are stored in the computer. In this section we will consider only text files. Binary files are considered in Chapter 11.

    File Input with the File and Scanner Classes

    An instance of the java.io.File class stores information that a Scanner object needs to create an input stream that is connected to the sequence of characters in a text file. A partial list of the public methods of the File class is given in the UML class diagram in Figure 4.26. We will need to use only the File() constructor in this section. The File instance created with the statement

     File theFile = new File("riddles.txt");

    will obtain and store information about the "riddles.txt" file in the same directory as the java code being executed, if such a file exists. If no such file exists, the File object stores information needed to create such a file but does not create it. In Chapter 11, we will describe how other objects can use a file object to create a file in which to write data. If we wish to create a File object that describes a file in a directory other than the one containing the Java program, we must call the constructor with a string argument that specifies the file’s complete path name—that is, one that lists the sequence of directories containing the file. In any case, while we will not use it at this time, the exists() method of a File instance can be used to determine whether or not a file has been found with the specified name.

    In order to read data from a file with a Scanner object we will need to use methods that were not discussed in Chapter 2. An expanded list of methods of the Scanner class is given in Figure 4.27. Note the there is a Scanner() constructor with a File object as an argument. Unlike the other create() method that was used in Chapter 2, this create() throws an exception that must be handled. The following code will create a Scanner object that will be connected to an input stream that can read from a file:

    try
    {   File theFile = new File("riddles.txt");
        fileScan = new Scanner(theFile);
        fileScan = fileScan.useDelimiter("\r\n");
    } catch (IOException e)
    {    e.printStackTrace();
    } //catch()

    We will discuss the try-catch commands when exceptions are covered in Chapter 10. Until then, the try-catch structures can be copied exactly as above, if you wish to use a Scanner object for file input. In the code above, the useDelimiter() method has been used to set the Scanner object so that spaces can occur in strings that are read by the Scanner object. For the definition of a class to read riddles from a file, the above code belongs in a constructor method.

    After we create a Scanner object connected to a file, we can make a call to nextInt(), nextDouble(), or next() method to read, respectively, an integer, real number, or string from the file. Unlike the strategy for using a Scanner object to get keyboard input, it is suggested that you test to see if there is more data in a file before reading it. This can be done with the hasNext(), hasNextInt(), and hasNextDouble() methods. These methods return the value true if there are more data in the file.

    The program in Figure [fig-fileprog] is the complete listing of a class that reads riddles from a file

    import java.io.*;
    import java.util.Scanner;
    public class RiddleFileReader
    {  private Scanner fileScan; // For file input
       private Scanner kbScan;   // For keyboard input
    
       public RiddleFileReader(String fName)
       {   kbScan = new Scanner(System.in);
           try
           {   File theFile = new File(fName);
               fileScan = new Scanner(theFile);
               fileScan = fileScan.useDelimiter("\r\n");
           } catch (IOException e)
           {    e.printStackTrace();
           } //catch()
       } //RiddleFileReader() constructor
       public Riddle readRiddle()
       {   String ques = null;
           String ans = null;
           Riddle theRiddle = null;
           if (fileScan.hasNext())
               ques = fileScan.next();
           if (fileScan.hasNext())
           {   ans =  fileScan.next();
               theRiddle = new Riddle(ques, ans);
           } // if
           return theRiddle;
       } // readRiddle()
       public void displayRiddle(Riddle aRiddle)
       {   System.out.println(aRiddle.getQuestion());
           System.out.print("Input any letter to see answer:");
           String str = kbScan .next();  //Ignore KB input
           System.out.println(aRiddle.getAnswer());
           System.out.println();
       } // displayRiddle()
       public static void main(String[] args)
       {   RiddleFileReader rfr =
               new RiddleFileReader("riddles.txt");
           Riddle riddle = rfr.readRiddle();
           while (riddle != null)
           {   rfr.displayRiddle(riddle);
               riddle = rfr.readRiddle();
           } // while
       } //main()
    }  //RiddleFileReader class

    and displays them. Note that, in the body of the method readRiddles(), the statements:

    String ques = null;
    String ans = null;
    Riddle theRiddle = null; 

    make explicit the fact that variables that refer to objects are assigned null as a value when they are declared. The statements:

    if (fileScan.hasNext())
        ques = fileScan.next();
    if (fileScan.hasNext())
    {   ans =  fileScan.next();
        theRiddle = new Riddle(ques, ans);
    } 

    will read Strings into the variables ques and ans only if the file contains lines of data for them. Otherwise the readRiddle() method will return a null value. The main() method uses this fact to terminate a while loop when it runs out of string data to assign to Riddle questions and answers. There is a separate method, displayRiddle() using a separate instance of Scanner attached to the keyboard to display the question of a riddle before the answer.

    The contents of the "riddles.txt" file should be a list of riddles with each question and answer on a separate line. For example The following three riddles saved in a text file would form a good example to test the RiddleFileReader class.

      What is black and white and red all over?
      An embarrassed zebra
      What is black and white and read all over?
      A newspaper
      What other word can be made with the letters of ALGORITHM?
      LOGARITHM

    When the main() method is executed, the user will see output in the console window that looks like:

      What is black and white and red all over?
      Input any letter to see answer: X
      An embarrassed zebra
      
      What is black and white and read all over?
      Input any letter to see answer:

    Files are covered in depth in Chapter 11. Information on writing data to a file and reading data from a file without using the Scanner class can be found in that chapter.

    Modify the RiddleFileReader class to create a program NumberFileReaderthat opens a file named "numbers.txt" and reports the sum of the squares of the integers in the file. Assume that the file "numbers.txt" contains a list of integers in which each integer is on a separate line. The program should print the sum of the squares in the System.out console window. In this case, there is no need to have a method to display the data being read or a Scanner object connected to the keyboard. You will want a constructor method and a method that reads the numbers and computes the sum of squares.

    abstract class

    abstract interface

    abstract method

    AWT

    binary file

    buffer

    command-line interface

    container

    control element

    event-driven programming

    event loop

    graphical user interface (GUI)

    helper method

    inheritance

    input operation

    input stream

    interface

    layout manager

    listener

    model-view-controller (MVC) architecture

    output operation

    output stream

    stream

    Swing

    text file

    top-level container

    user interface

    wrapper class

    An input operation is any action that transfers data from the user to the computer’s main memory via one of the computer’s input devices. An output operation is any action that transfers data from the computer’s main memory to one of the computer’s output devices.

    The user interface is that part of the program that handles the input and output interactions between the user and the program. As an interface, it limits or constrains the manner in which the user can interact with the program.

    In a command-line interface, user input is taken from the keyboard, and the program’s output is displayed on some kind of console.

    A buffer is a portion of main memory where input is held until it is needed by the program. Using a buffer between the keyboard and the program allows you to use the Backspace key to delete a character.

    A wrapper class contains methods for converting primitive data into objects and for converting data from one type to another.

    Designing appropriate prompts is an important aspect of designing a good user interface.

    I/O operations must watch out for certain types of I/O exceptions.

    GUI programming involves a computational model known as event-driven programming, which means that GUI programs react to events that are generated mostly by the user’s interactions with elements in the GUI.

    Java has two packages of GUIs, the older java.awt and the newer javax.swing.

    Swing components are based on the object-oriented model-view-controller (MVC) architecture.

    The extends keyword is used to specify subclass/superclass relationships in the Java class hierarchy.

    A top-level container is a GUI container that cannot be added to another container; it can only have components added to it. All GUI programs must be contained in a top-level container.

    There are generally three kinds of GUI components, corresponding to the three main functions of a user interface: input, output, and control.

    Events are handled by special objects called listeners. A listener is a specialist that listens constantly for a certain type of event.

    An interface is a special Java class that contains only methods and constants (final variables).

    The following modification of the GreeterApp class is an implementation of the High Low Game:

    %%%[basicstyle=\scriptsize]
    public class HighLowApp 
    { private KeyboardReader reader;
      private int secretNumber;
    
      public HighLowApp() 
      { reader = new KeyboardReader();
        secretNumber = 1 + (int)(Math.random() * 100);
      } // HighLowApp() constructor
        
      public void run() 
      { int userGuess = -1;
        reader.display("Guess my secret number between 1 and 100.");
        while (userGuess != secretNumber)
        {   reader.prompt("Please input your guess here > ");
          userGuess = reader.getKeyboardInteger();
          if (userGuess > secretNumber)
            reader.display("Your guess was too high.");
          if (userGuess < secretNumber)
            reader.display("Your guess was too low.");
        } // while
        reader.display("Congratulations. Your guess was correct.");
      } // run()
         
      public static void main(String args[]) 
      { HighLowApp app = new HighLowApp();
        app.run();
      } // main()
    }// HighLowApp

    The following modification of GreeterGUI eliminates the JButton.

    %%%[basicstyle=\scriptsize]
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class GreeterGUI2 extends JFrame 
                             implements ActionListener 
    { private JTextArea display;
      private JTextField inField;
      private Greeter greeter;
            
      public GreeterGUI2(String title) 
      {   greeter = new Greeter();  
          buildGUI();
          setTitle(title);
          pack();
          setVisible(true);
      } // GreeterGUI2()
      private void buildGUI() 
      {   Container contentPane = getContentPane();
          contentPane.setLayout(new BorderLayout());
          display = new JTextArea(10,30);
          inField = new JTextField(10);
          inField.addActionListener(this);
          JPanel inputPanel = new JPanel();
          inputPanel.add(new 
                  JLabel("Input your name and type enter: "));
          inputPanel.add(inField);
          contentPane.add("Center", display);
          contentPane.add("South", inputPanel);
      } // buildGUI()
      public void actionPerformed(ActionEvent e) 
      {   if (e.getSource() == inField) 
          {   String name = inField.getText();
              display.append(greeter.greet(name) + "\n");
          }
      } // actionPerformed()
    } // GreeterGUI2

    Java code that prints out the sum of the squares of a set of integers read from a file named "numbers.txt":

    %%%[basicstyle=\scriptsize]
    import java.io.*;
    import java.util.Scanner;
    
    public class NumberFileReader
    {   private Scanner fileScan; // For file input
       
        public NumberFileReader(String fName)
        {   try
            {   File theFile = new File(fName);
                fileScan = new Scanner(theFile);
            } catch (IOException e)
            {    e.printStackTrace();
            } //catch()
        } //NumberFileReader() 
    
        public void readNumbers()
        {   int num = 0;      // To store integers read
            int sum = 0:      // To store sum of squares
            while (fileScan.hasNextInt()) 
            {   num = fileScan.nextInt();
                sum = sum + num * num;
            } // while
            System.out.println("The sum of squares = " + sum);
        } // readNumbers()
    
        public static void main(String[] args)
        {   NumberFileReader nfr =
                new NumberFileReader("numbers.txt");
            nfr.readNumbers()
        } //main()
    }  //NumberFileReader 

    Fill in the blanks in each of the following sentences:

    =13pt

    An


    is a Java program that can be embedded in a Web page.

    A method that lacks a body is an


    method.

    An


    is like a class except that it contains only instance methods, no instance variables.

    In a Java class definition a class can


    a class and


    an interface.

    Classes and methods not defined in a program must be


    from the Java class library.

    A subclass of a class inherits that class’s


    instance variables and instance methods.

    An object can refer to itself by using the


    keyword.

    The JButton, JTextField, and JComponent classes are defined in the


    package.

    Java GUIs utilize a form of control known as


    programming.

    When the user clicks on a program’s JButton, an


    will automatically be generated.

    Two kinds of objects that generate ActionEvents are


    and


     .

    JButtons, JTextFields, and JLabels are all subclasses of


     .

    The JFrame class is a subclass of


     .

    If java class intends to handle ActionEvents, it must implement the


    interface.

    When an applet is started, its


    method is called automatically.

    =11pt

    Explain the difference between the following pairs of concepts:

    Class and interface.

    Extending a class and instantiating an object.

    Defining a method and implementing a method.

    A protected method and a public method.

    A protected method and a private method.

    An ActionEvent and an ActionListener() method.

    Draw a hierarchy chart to represent the following situation. There are lots of languages in the world. English, French, Chinese, and Korean are examples of natural languages. Java, C, and C++ are examples of formal languages. French and Italian are considered romance languages, while Greek and Latin are considered classical languages.

    Arrange the Java library classes mentioned in the Chapter Summary into their proper hierarchy, using the Object class as the root of the hierarchy.

    Look up the documentation for the JButton class on Sun’s Web site:

    http://java.sun.com/j2se/1.5.0/docs/api/

    List the signatures of all its constructors.

    Suppose we want to set the text in our program’s JTextField. What method should we use and where is this method defined? (Hint: Look up the documentation for JTextField. If no appropriate method is defined there, see if it is inherited from a superclass.)

    Does a JApplet have an init() method? Explain.

    Does a JApplet have an add() method? Explain.

    Does a JButton have an init() method? Explain.

    Does a JButton have an add() method? Explain.

    Suppose you type the URL for a “Hello, World!” applet into your browser. Describe what happens—that is, describe the processing that takes place in order for the applet to display “Hello, World!” in your browser.

    Suppose you have a program containing a JButton named button. Describe what happens, in terms of Java’s event handling model, when the user clicks the button.

    Java’s Object class contains a public method, toString(), which returns a string that represents this object. Because every class is a subclass of Object, the toString() method can be used by any object. Show how you would invoke this method for a JButton object named button.

    The JFrame that follows contains a semantic error in its SomeFrame() constructor. The error will cause the actionPerformed() method never to display “Clicked” even though the user clicks the button in the JFrame. Why? (Hint: Think scope!)

    public class SomeFrame extends JFrame
                            implements ActionListener
    {
         // Declare instance variables
        private JButton button;
    
        public JFrame()
        {   
           // Instantiate the instance variable
            JButton button = new JButton("Click me");
            add(button);
            button.addActionListener(this);
        } // init()
    
        public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == button)
               System.out.println("Clicked");
        } // actionPerformed()
    } // SomeFrame

    What would be output by the following program?

    public class SomeFrame2 extends JFrame
    {
      // Declare instance variables
      private JButton button;
      private JTextField field;
    
      public SomeFrame()
      { 
        // Instantiate instance variables
        button = new JButton("Click me");
        add(button);
        field = new JTextField("Field me");
        add(field);
        System.out.println(field.getText() + button.getText());
      } // init()
      public static void main(String[] args) {
         SomeFrame2 frame = new SomeFrame2();
         frame.setSize(400,400);
         frame.setVisible(true);
      }
    } // SomeFrame2
    }

    Design and implement a GUI that has a JButton, a JTextField, and a JLabel and then uses the toString() method to display each object’s string representation.

    The JButton class inherits a setText(String s) from its AbstractButton() superclass. Using that method, design and implement a GUI that has a single button labeled initially, “The Doctor is out.” Each time the button is clicked, it should toggle its label to, “The Doctor is in” and vice versa.

    Design and implement a GUI that contains two JButtons, initially labeled, “Me first!” and “Me next!” Each time the user clicks either button, the labels on both buttons should be exchanged. (Hint: You don’t need an if-else statement for this problem.)

    Modify the GUI in the previous exercise so that it contains three JButtons, initially labeled “First,” “Second,” and “Third.” Each time the user clicks one of the buttons, the labels on the buttons should be rotated. Second should get first’s label, third should get second’s, and first should get third’s label.

    Design and implement a GUI that contains a JTextField and two JButtons, initially labeled “Left” and “Right.” Each time the user clicks a button, display its label in the JTextField. A JButton()’s label can be gotten with the getText() method.

    You can change the size of a JFrame by using the setSize(int h, int v) method, where h and v give its horizontal and vertical dimensions pixels. Write a GUI application that contains two JButtons, labeled “Big” and “Small.” Whenever the user clicks on small, set the JFrame’s dimensions to 200 \(\times\) 100, and whenever the user clicks on big, set the dimensions to 300 \(\times\) 200.

    Rewrite your solution to the previous exercise so that it uses a single button whose label is toggled appropriately each time it is clicked. Obviously, when the JButton is labeled “Big,” clicking it should give the JFrame its big dimensions.

    Challenge: Design and write a Java GUI application that allows the user to change the JFrame’s background color to one of three choices, indicated by buttons. Like all other Java Components, JFrame’s have an associated background color, which can be set by the following commands:

    setBackground(Color.red);
    setBackground(Color.yellow);

    The setBackground() method is defined in the Component class, and 13 primary colors—black, blue, cyan, darkGray, gray, green, lightGray, , orange, pink, red, white, yellow—are defined in the java.awt.Color class.

    Given the classes with the following headers

    public class Animal ...
    public class DomesticAnimal extends Animal ...
    public class FarmAnimal extends DomesticAnimal...
    public class HousePet extends DomesticAnimal...
    public class Cow extends FarmAnimal ...
    public class Goat extends FarmAnimal ...
    public class DairyCow extends Cow ...

    draw a UML class diagram representing the hierarchy created by these

    Given the preceding hierarchy of classes, which of the following are legal assignment statements?

    DairyCow dc = new FarmAnimal();
    FarmAnimal fa = new Goat();
    Cow c1 = new DomesticAnimal();
    Cow c2 = new DairyCow();
    DomesticAnimal dom = new HousePet();

    This page titled 4.5: From the Java Library- java.io.File and file input (Optional) is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.