FILE input/output in java

     source->a stream->reads->program
     program->writes->a stream->dest

   – I/O is stream of bytes
     – Whole number of bytes
• Here: byte ->character
Stream: an object that either
       – delivers data to its destination (screen, file, etc.) or
       – that takes data from a source (keyboard, file, etc.)
• Acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program
     – is an input stream
• Output stream: a stream that accepts output from a program
     – System.out is an output stream
• A stream connects a program to an I/O object
      – System.out connects a program to the screen
      – connects a program to the keyboard

• In Languages prior to Java
   – Character = 8bits
   – ASCII character set
In Java
  – 16 bit

I/O overview
• In this context it is input to and output from
• Input can be from keyboard or a file
• Output can be to display (screen) or a file
Advantages of file I/O
      – permanent copy
      – output from one program can be input to another

• All data and programs are ultimately just zeros
and ones
    – Each digit can have one of two values, hence
    – Bit is one binary digit
    – Byte is a group of eight bits

Text files: The bits represent printable
     – One byte per character for ASCII, the most
        common code
     – For example, Java source files are text files
     – So is any file created with a "text editor"

• Binary files: The bits represent other types of
 encoded information
      – For example, executable instructions or numeric data
• These files are easily read by the computer but
not humans
• They are not "printable" files
        – Actually, you can print them, but they will be illegible
        – “Printable" means "easily readable by humans when

Text Files
• Clean Text (.txt) files are the simplest kind of
 – Text files can be used by many different programs
• Formatted text files (e.g. .doc files) also
contain binary formatting information
– Programs that know how to read these codes can use such files
• Compilers, in general, work only with text
• Reading data from keyboard using scanner
– Scanner kybd = new Scanner(;
– width = kybd.nextInt();

Advantage of Using Files
• Stored Data can be read from file
• Data can be stored permanently in file
• Data can be shared by multiple programs

File Class
• Part of
• Does not operate on streams
      – Unlike other classes in
• Describes the properties of a “file”
• Obtain / Manipulate information like
     – Permissions, date and time, directory path etc.
• Directory is treated as a File
     – List of filenames (additional property)

• Usages
– File(String directoryPath)
– File(String directoryPath, String fileName)
– File(File dirObj, String fileName)
– File(URI uriObj) (since Java 2, ver 1.4)

• Example
– File D1 = new File(“/”);
– File D2 = new File(“/”, “testFile.txt”);
– File D2 = new File(D1, “testFile.txt”);

Reading from File
• Must import*
• Create a Scanner object to read from a file
– Use the name of the file to read in place of
– File must be in same folder as Java program
• Else, checked exception will occur
– checked exception must be handled
– can have any number of Scanner objects
• one to read from each file
• one to read from keyboard
• When processing is done: all files should be
• Scanner object methods are used to read from
file in same way as they read from keyboard:
      – nextInt()
      – nextDouble()
      – next()
      – nextLine()
• hasNext() method:
     – returns true if there is more data to read
     – returns false when end of file is reached
     – can use hasNext() method in a while loop to process
       all data in a file

//input ages from file and calculate average
import java.util.*;
public class AverageAge
public static void main (String [] args)
double sum = 0;
int count = 0;
//create Scanner linked to input file
Scanner in = new Scanner(new File("in.txt"));
String name;
double age;

//read until end of file reached
while (in.hasNext())
name =;
age = in.nextDouble();

sum = sum + age;
//close file
double average = sum / count;
System.out.println("The average age is: " + average);
//handle any errors
catch(ArithmeticException e)
System.out.println("Cannot calculate average - no data");
catch(IOException e)
System.out.println("Error reading from file");

Buffering of I/O
• Not Buffered
     – Each byte is read from or written to disk
     – Some delay for each byte
     – High overhead
• Buffered
     – Chunk of bytes are accessed (read/write) in the
     – Disk operation: per buffer-size
• Low overhead

Open a Stream
• Creating connection to external data
• After connecting, no need to remember the
actual location or the file name
• A FileReader is a used to connect to a file
that will be used for input:
FileReader fileReader =
new FileReader(fileName)
• fileName refers to the name and the external
location of the file. 

• FileReader file = new FileReader("C:\\testing.txt")
• Above is Windows style declaration
• As ‘\’ is the escape character, “\\” must be
written to represent single \
Linux style:
• FileReader file = new FileReader("bin/ testing.txt "); 

Use the Stream
• Read OR Write
• May need to manipulate the data
int charAsInt;
charAsInt = );
• The method reads one
character at a time and
     – returns it as an integer,
     – or -1 if there are no more characters to read 
• Meaning of the data depends on the file
encoding technique used in that file
   – E.g While reading an ASCII file, 97 will mean “a”
• The input can be typecast to char
char ch = (char) ); 
• Instead of “Not Buffered” method, it is
preferred to use “Buffered” methods to read
      – And a way to read files as a stream of characters
• A BufferedReader will read chunk of data at
a time
     – convert integers to characters too 

Reading Lines
• The constructor for BufferedReader takes a
FileReader parameter:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
Reading a Line:
String s;
s = bufferedReader.readLine( );

• Return null if there is nothing more to read 

Close the Stream
• Should close the file after work
• Use the close() method of BufferedReader
class to close the stream
• If the program ends normally, it will close all
the streams automatically 

Then Why Bother Closing??
• There is a limit on the number of streams that
you can have open at one time
• You must close a stream before you can open
it again
• It could get damaged if left open and the
program terminates abnormally 

Writing to File
must import*
• create a PrintWriter object to write to a file
        – need the name of the file to write to
        – file will be in same folder as Java program
     • if file already exists contents will be overwritten
     • if file doesn't exist, new one is created
       – checked exception must be handled
• can have any number of PrintWriter objects 

• PrintWriter object methods are used to write
data to file:
    – print()
    – println()
    – printf() 
//input numbers and output odd ones to odd.txt, even ones to even.txt
import java.util.*;
public class OddsEvens
public static void main (String [] args)
//create PrintWriters linked to output files
Scanner kybd = new Scanner(;
PrintWriter even = new PrintWriter("even.txt");
PrintWriter odd = new PrintWriter("odd.txt");
int num = kybd.nextInt();
//read until -1 entered
while (num != -1)
if (num % 2 != 0)
num = kybd.nextInt();
//close files
catch(IOException e)
System.out.println("Error writing to file"); }

Related Posts