Accepting Values From File in Java

In the previous tutorial, we covered how to create a text file in Java, and then store values in it. First, let's create a simple program that stores two values in a text file.
  1. import java.io.*;
  2.  
  3. public class output
  4. {
  5.  
  6.         public static void main(String[] args)
  7.         {
  8.  
  9.                 try
  10.                 {
  11.                         File newTextFile = new File("data.txt");
  12.  
  13.                         FileWriter toFile = new FileWriter(newTextFile);
  14.  
  15.                         int hours = 35;
  16.  
  17.                         int pay = 15;
  18.  
  19.                         toFile.write(String.valueOf(hours));
  20.  
  21.                         toFile.write("\n");
  22.  
  23.                         toFile.write(String.valueOf(pay));
  24.  
  25.                         toFile.close();
  26.  
  27.                 }
  28.  
  29.                 catch (IOException e)
  30.                 {
  31.                 }
  32.        
  33.         }
  34. }
You may save this and run it first. You will need the text file it creates for later on. As you can see, it lists a number of hours worked, and the pay rate. You may edit this so that the user can enter the values themselves by use of a scanner. For help on using a scanner, click here. Now that we have our text file with values saved, we can retrieve those values from within another class. First of all, make sure you save both .java files in the same folder, as they are set to read and write from the same one.
  1. import java.util.Scanner; //necessary for scanner object
  2. import java.io.*; //necessary for reading from file
  3.  
  4. public class dataretrieval
  5. {
  6.         public static void main(String[] args) throws FileNotFoundException //exception needed or program will not run
  7.         {
  8.  
  9.                 Scanner readFile = new Scanner(new FileReader("data.txt")); //creation of scanner that reads data.txt
  10.  
  11.                 double hours;
  12.                 double pay;
  13.  
  14.                 hours = readFile.nextDouble(); //sets the first value to hours and second to pay
  15.                 pay = readFile.nextDouble();
  16.                 double earnings = hours * pay; //calculates earnings for the period
  17.  
  18.                 System.out.println("\nYour weekly earnings for the week are " + earnings + "\n");
  19.         }
  20. }
Sending and retrieving data from external files is very commonplace in programming. For example, when a game is saved, the current status stored, and then it is retrieved once again when the player comes back to the game. Knowing how to send and retrieve data is a very useful coding skill to have. Be sure to read through the comments and experiment variations of the program on your own to be sure you understand it!
Tags

Add new comment