Accepting Values From File in Java
Submitted by GeePee on Wednesday, May 13, 2015 - 23:16.
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.
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.
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!
- import java.io.*;
- public class output
- {
- {
- try
- {
- int hours = 35;
- int pay = 15;
- toFile.write("\n");
- toFile.close();
- }
- {
- }
- }
- }
- import java.util.Scanner; //necessary for scanner object
- import java.io.*; //necessary for reading from file
- public class dataretrieval
- {
- public static void main(String[] args) throws FileNotFoundException //exception needed or program will not run
- {
- Scanner readFile = new Scanner(new FileReader("data.txt")); //creation of scanner that reads data.txt
- double hours;
- double pay;
- hours = readFile.nextDouble(); //sets the first value to hours and second to pay
- pay = readFile.nextDouble();
- double earnings = hours * pay; //calculates earnings for the period
- }
- }
Add new comment
- 10 views