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(input.txt);
Scanner input = new Scanner(reader);
PrintWriter output = new PrintWriter(output.txt);
output.println(Java Programming);
output.println(C# Programming);
output.close();
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 testIn.txt. 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.
java.util.*;
java.io.*;
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("testIn.txt"));
// the same =>Scanner in = new Scanner(new File("testIn.txt"));
while (in.hasNext()) {
num = in.nextInt();
tot += num;
bil++;
}
average=tot/bil;
System.out.println("Total is " + tot);
System.out.println("Average is " + average);
in.close();
}
}
Example 2: Program to write data to a text file.
//this program will write data
import java.util.*;
import java.io.*;
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("outTest2.txt"));
for(i=1;i<=10;i++){
output.print(i+ " ");//print to file
//S.O.P(i+ ); to your screen
}
output.close();
}
Lab Exercise: Write a program to accept user input of length in kilometer from console and
store it in a text file named KMData.txt. Read the text file and convert it to meter. Store the
new data in mdata.txt. Display the data in kilometer and meter at console (screen).