File Input/Output Basic Java Tutorial - Get an output to a file using java.io.PrintWriter
Coding River
File Input/Output Basic Java Tutorial - Get an output using java.io.PrintWriter
In this video, we are going to see how to send the output of a java program to a file stored on your local computer. This way of doing becomes useful when we want to get the output of a program in a printed format. In order to do that, we are going to use the class PrintWriter. This class is also contained in the package java.io
Now, let me show you how this works, with the help of an example Suppose that we have an input file here MyFile.txt which is consisting of the following data and this data correspond to the first name, the name, the age and the height of a person As you can see on the screen, I have already declared the appropriate variables to get the input from the input file MyFile.txt and I am storing that input data into the variables
The first line of code : Scanner input_file = new Scanner(new FileReader("C:\Users\Test\Documents\MyFile.txt")); is used to create and associate the Scanner object to the input source The String variable firstname is used to store the first name The variable name is going to store the name and the method next() is used to get the input value form the source that is Myfile The variable age will store the age And the variable height is used to store the height
We are using these predefined methods to get the input values from the file
Now, as I said at the beginning, in order to store the output of a program in a file, you have to use the class PrintWriter I will start by declaring a PrintWriter variable and associate this variable with the destination that is the file where the output will be stored
PrintWriter output_file = new PrintWriter(“c:\Users\OutputFile.txt”); What this statement will do is that it will create the PrintWriter object output_file and associate it with the file OutputFile.txt Always make sure that you are writing the correct path to the file and using two backward slashes because of the escape character sequence rules
After that, you can now use the predefined methods print or println with the output file Instead of writing System.out.println() We will rather write the name of the output object, in our case here it is output_file.println(“My name is : “ + firstname + “ “ + name); Once the output statement is done, we have to close the file using the close method Let’s write output_file.close(); This will ensure that the buffer holding the output will be emptied and the entire output generated by the program will be sent to the output file
If I run the program now, the value inside the brackets will be stored in the output file OutputFile Open the output file, and see that we have My name is : John Doe The statement assumes that the values stored in the variable firstname and name ... https://www.youtube.com/watch?v=MumrTW3Nc8g
14349205 Bytes