Week 8 File Input/Output
Files can be used to permanently store data created in a program.
Example of files are text editors, Java source codes and HTML
files. Use the Scanner class to read text files and the PrintWriter
class to create and write data to a text file. When you are done
processing a file, close the Scanner or Printwriter using the
close() method.
Here is an example.
FileReader reader = new FileReader([Link]);
Scanner input = new Scanner(reader);
PrintWriter output = new PrintWriter([Link]);
[Link](Java Programming);
[Link](C# Programming);
[Link]();
MORE EXAMPLES
Tutorial 1 : A program will read data from text file and print the output to console.
a.
b.
//this
import
import
Create the text file in notepad. Save with [Link]. Make sure the file is in the same folder
Writeand run the following code.
program will read data from text file and print the output to console.
[Link].*;
[Link].*;
public class ReadFromFile {
public static void main(String[] args) throws Exception {
double tot = 0;
int bil=0;
int num;
double average;
Scanner in = null;
in = new Scanner(new File("[Link]"));
// the same =>Scanner in = new Scanner(new File("[Link]"));
while ([Link]()) {
num = [Link]();
tot += num;
bil++;
}
average=tot/bil;
[Link]("Total is " + tot);
[Link]("Average is " + average);
[Link]();
}
}
Example 2: Program to write data to a text file.
//this program will write data
import [Link].*;
import [Link].*;
to a text file.
public class loopToFile {
public static void main(String[] args) throws
Exception {
int i;
PrintWriter output = null;
output = new PrintWriter(new
File("[Link]"));
for(i=1;i<=10;i++){
[Link](i+ " ");//print to file
//S.O.P(i+ ); to your screen
}
[Link]();
}
Lab Exercise: Write a program to accept user input of length in kilometer from console and
store it in a text file named [Link]. Read the text file and convert it to meter. Store the
new data in [Link]. Display the data in kilometer and meter at console (screen).