Java || Snippet – How To Read & Write Data From A File

Print Friendly, PDF & Email

This page will consist of a demonstration of a simple quadratic formula program, which highlights the use of the input/output mechanisms of manipulating a text file. This program will read in data from a file (numbers), manipulate that data, and output new data into a different text file.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Try/Catch - What Is It?
The "Math" Class - sqrt and pow
The "Scanner" Class - Used for the input file
The "FileWriter" Class - Used for the output file
The "File" Class - Used to locate the input/output files
Working With Files

NOTE: The data file that is used in this example can be downloaded here.

In order to read in the data .txt file, you need to save the .txt file in the same directory (or folder) as your .java file is saved in. If you are using Eclipse, the default directory will probably be:


Documents > Workspace > [Your project name]

Alternatively, you can execute this command, which will give you the current directory in which your source file resides:


System.out.println(System.getProperty("user.dir"));

Whatever the case, in order to read in the data .txt file, your program must know where it is located on the system.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Remember to include the example input file)

Welcome to My Programming Notes' Java Program.

For the numbers:
a = 2.0
b = 4.0
c = -16.0

root 1 = 2.0
root 2 = -4.0

Program Success!!

Was this article helpful?
👍 YesNo

Leave a Reply