Java || Snippet – How To Read & Write Data From A File
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
import java.io.File; // used to locate the input/output files import java.io.FileWriter; // used for file output import java.util.Scanner; // used for file input public class ReadWriteFile { public static void main(String[] args) { // declare & initialize variables Scanner infile; FileWriter outfile; double a=0,b=0,c=0; double root1=0, root2=0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // use a try/catch to check to see if the input file exists, & if not then EXIT try { // this opens the input file // YOUR INPUT FILE NAME GOES BELOW infile = new Scanner(new File("INPUT_Quadratic_programmingnotes_freeweq_com.txt")); // this opens the output file // if the file doesnt already exist, it will be created outfile = new FileWriter(new File("OUTPUT_Quadratic_programmingnotes_freeweq_com.txt")); // if the file was found, this try/catch will execute, and the loop will // attempt to get the 3 numbers from the input file and place // them inside the variables 'a,b,c' try { while(infile.hasNext()) { // this assigns the incoming data to the // variables 'a', 'b' and 'c' // NOTE: it is just like a normal scanner statement a = infile.nextInt(); b = infile.nextInt(); c = infile.nextInt(); // NOTE: if you want to read in data into an array // your declaration would be like this // ------------------------------------ // a[counter] = infile.nextInt(); // b[counter] = infile.nextInt(); // c[counter] = infile.nextInt(); // ++counter; } } catch(Exception e) { // if there was an error on input, (i.e the input file contains letters) // this block will execite, and the program will exit System.err.println("There is a formatting error in the input file!n" + "The input file should contain only 3 numbersn"); System.exit(1); } // this does the quadratic formula calculations root1 = ((-b) + Math.sqrt(Math.pow(b,2) - (4*a*c)))/(2*a); root2 = ((-b) - Math.sqrt(Math.pow(b,2) - (4*a*c)))/(2*a); // this displays the numbers to screen via stdout System.out.println("For the numbers:na = "+a+"nb = "+b+"nc = "+c); System.out.println("nroot 1 = "+root1+"nroot 2 = "+root2); // this saves the data to the output file // NOTE: its almost exactly the same as the above print statement, except // the 'write' function is dependent on the "newline" (NL) method // to generate a line break String NL = System.getProperty("line.separator"); outfile.write("For the numbers:"+NL+"a = "+a+NL+"b = "+b+NL+"c = "+c); outfile.write(NL+NL+"root 1 = "+root1+NL+"root 2 = "+root2); // close the input/output files once you are done using them infile.close(); outfile.close(); } catch(Exception e) { // if the file cannot be found, this block will execute, and the // program will exit System.err.println("Error, the input file could not be found!n" +e.getMessage()); System.exit(1); } System.out.println("nProgram Success!!n"); }// end of main }// http://programmingnotes.org/ |
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.0root 1 = 2.0
root 2 = -4.0Program Success!!
Leave a Reply