SlideShare a Scribd company logo
WIX1002
Fundamentals of Programming
Chapter 7
File Input and Output
Contents
 Introduction
 Writing to Text File
 Reading from Text File
 File Class
 Writing to Binary File
 Reading from Binary File
Introduction
 Files are used for permanent storage of large amounts
of data
 Text file is file that contains sequence of characters. It
is sometimes called ASCII files because the data are
encoded using ASCII coding.
 Binary file stores data in binary format. The data are
stored in the sequence of bytes.
 A stream is a flow of data. If the data flows into the
program, the stream is input stream. If the data flows
out of the program, the stream is output stream.
Writing to Text File
 PrintWriter class is used to write data to a text file.
 PrintWriter streamObject = new PrintWriter(new
FileOutputStream(FileName));
 Close the file after finish writing using
streamObject.close() method.
 The PrintWriter, FileOutputStream and IOException
class need to be loaded using the import statement.
Writing to Text File
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;
try {
PrintWriter outputStream = new PrintWriter(new
FileOutputStream("data.txt"));
…
outputStream.close();
} catch (IOException e) {
System.out.println(“Problem with file output");
}
Writing to Text File
 After the outputStream has been declared, print, println
and printf can be used to write data to the text file.
 To write to the file on a specified directory,
 PrintWriter outputStream = new PrintWriter(new
FileOutputStream("d:/sample/data.txt"));
 To append to a text file
 To write to the end of the file,
 PrintWriter outputStream = new PrintWriter(new
FileOutputStream("d:/sample/data.txt", true));
Exercise
Write a program to store the exchange rate to
the text file named currency.txt
USD 0.245
EUR 0.205
GBP 0.184
AUD 0.332
THB 7.41
Reading from Text File
 Two most common stream classes used for reading text
file are the Scanner class and BufferReader class.
 Scanner streamObject = new Scanner (new
FileInputStream(FileName));
 Close the file after finish reading using
streamObject.close() method.
 The FileInputStream and FileNotFoundException
class need to be loaded using the import statement.
Reading from Text File
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
try {
Scanner inputStream = new Scanner(new
FileInputStream("data.txt"));
…
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File was not found");
}
Reading from Text File
 After the inputStream has been declared, nextInt,
nextDouble, nextLine can be used to read data from
the text file.
String input = inputStream.nextLine();
int num1 = inputStream.nextInt();
double num2 = inputStream.nextDouble();
 To check for the end of a text file
 while (inputStream.hasNextLine())
 To open file from a specified directory
 Scanner inputStream = new Scanner(new
FileInputStream("d:/sample/data.txt"));
Reading from Text File
 BufferedReader class is another class that can read text
from the text file.
 BufferedReader inputStream = new BufferedReader(
new FileReader(FileName));
 Close the file after finish reading using
streamObject.close() method.
 The BufferedReader, FileReader and
FileNotFoundException, IOException class need to be
loaded using the import statement.
Reading from Text File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
try {
BufferedReader inputStream = new BufferedReader (new
FileReader("data.txt"));
…
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File was not found");
} catch (IOException e) {
System.out.println(“Error reading from file");
}
Reading from Text File
 After the inputStream has been declared, read and
readLine can be used to read data from the text file.
String input = inputStream.readLine();
 To check for the end of a text file
 while ( (input=inputStream.readLine()) != null)
 To open file from a specified directory
 BufferedReader inputStream = new BufferedReader(
new FileReader("d:/sample/data.txt"));
Example
Write a program to read the exchange rate from
currency.txt and compute the exchange rate
File Class
 File class contains methods that used to check the
properties of the file.
 The file class is loaded using import java.io.File;
File fileObject = new File("data.txt");
if (fileObject.exists()) {
System.out.println("The file is already exists");
fileObject.renameTo("data1.txt");
}
if (fileObject.canRead())
System.out.println("The file is readable");
if (fileObject.canWrite())
System.out.println("The file is writable");
Writing to Binary File
 ObjectOutputStream is the stream class that used to
write data to a binary file.
 ObjectOutputStream streamObject = new
ObjectOutputStream (new FileOutputStream(FileName));
 The ObjectOutputStream, FileOutputStream and
IOException class need to be loaded using the import
statement.
 The writeInt, writeDouble, writeChar, writeBoolean
can be used to write the value of different variable type
to the output stream. Use writeUTF to write String object
to the output stream.
 Close the file after finish writing using
streamObject.close() method.
Writing to Binary File
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
try {
ObjectOutputStream outputStream = new
ObjectOutputStream (new FileOutputStream("data.dat"));
…
outputStream.close();
} catch (IOException e) {
System.out.println("Problem with file output.");
}
Reading from Binary File
 ObjectInputStream is the stream class that used to
read a binary file written using ObjectOutputStream
 ObjectInputStream streamObject = new
ObjectInputStream (new FileInputStream(FileName));
 The ObjectInputStream, FileInputStream and
IOException, FileNotFoundException class need to be
loaded using the import statement.
 The readInt, readDouble, readChar, readBoolean can
be used to read the value from the input stream. Use
readUTF to read String object from the input stream.
 Close the file after finish writing using
streamObject.close() method.
Reading from Binary File
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
try {
ObjectInputStream inputStream = new ObjectInputStream (new
FileInputStream("data.dat"));
…
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File was not found");
} catch (IOException e) {
System.out.println("Problem with file input.");
}
Reading from Binary File
 To check for the end of a text file
 Use EOFException
try {
while(true) {
number = inputStream.readInt();
}
} catch (EOFException e) { }
Exercise
 Generate N random numbers within 10-100, N is within
(20-30) and then store in a binary file number.dat.
 Read all the random numbers from number.dat
 Display all the numbers, N, maximum and minimum
File Input and Output in Java Programing language

More Related Content

Similar to File Input and Output in Java Programing language (20)

DOCX
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
PPT
Java căn bản - Chapter12
Vince Vo
 
PPT
Chapter 12 - File Input and Output
Eduardo Bergavera
 
PPTX
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
PPTX
File Handling in Java Oop presentation
Azeemaj101
 
PPTX
File Handling.pptx
PragatiSutar4
 
PDF
Absolute Java 5th Edition Walter Savitch Solutions Manual
labakybrasca33
 
PDF
Lecture 11.pdf
SakhilejasonMsibi
 
PPT
ch09.ppt
NiharikaDubey17
 
PDF
OOPs with Java_unit2.pdf. sarthak bookkk
Sarthak964187
 
PPTX
Java I/O
Jayant Dalvi
 
PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PDF
Java IO Stream, the introduction to Streams
ranganadh6
 
DOCX
FileHandling.docx
NavneetSheoran3
 
PPTX
Chapter 10.3
sotlsoc
 
PDF
Basic i/o & file handling in java
JayasankarPR2
 
PPTX
Files io
Narayana Swamy
 
PPTX
Java Tutorial Lab 6
Berk Soysal
 
PDF
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
PPS
Files & IO in Java
CIB Egypt
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
Java căn bản - Chapter12
Vince Vo
 
Chapter 12 - File Input and Output
Eduardo Bergavera
 
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
File Handling in Java Oop presentation
Azeemaj101
 
File Handling.pptx
PragatiSutar4
 
Absolute Java 5th Edition Walter Savitch Solutions Manual
labakybrasca33
 
Lecture 11.pdf
SakhilejasonMsibi
 
ch09.ppt
NiharikaDubey17
 
OOPs with Java_unit2.pdf. sarthak bookkk
Sarthak964187
 
Java I/O
Jayant Dalvi
 
File Handling in Java.pdf
SudhanshiBakre1
 
Java IO Stream, the introduction to Streams
ranganadh6
 
FileHandling.docx
NavneetSheoran3
 
Chapter 10.3
sotlsoc
 
Basic i/o & file handling in java
JayasankarPR2
 
Files io
Narayana Swamy
 
Java Tutorial Lab 6
Berk Soysal
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
Files & IO in Java
CIB Egypt
 

Recently uploaded (20)

PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Python basic programing language for automation
DanialHabibi2
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Ad

File Input and Output in Java Programing language

  • 2. Contents  Introduction  Writing to Text File  Reading from Text File  File Class  Writing to Binary File  Reading from Binary File
  • 3. Introduction  Files are used for permanent storage of large amounts of data  Text file is file that contains sequence of characters. It is sometimes called ASCII files because the data are encoded using ASCII coding.  Binary file stores data in binary format. The data are stored in the sequence of bytes.  A stream is a flow of data. If the data flows into the program, the stream is input stream. If the data flows out of the program, the stream is output stream.
  • 4. Writing to Text File  PrintWriter class is used to write data to a text file.  PrintWriter streamObject = new PrintWriter(new FileOutputStream(FileName));  Close the file after finish writing using streamObject.close() method.  The PrintWriter, FileOutputStream and IOException class need to be loaded using the import statement.
  • 5. Writing to Text File import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.IOException; try { PrintWriter outputStream = new PrintWriter(new FileOutputStream("data.txt")); … outputStream.close(); } catch (IOException e) { System.out.println(“Problem with file output"); }
  • 6. Writing to Text File  After the outputStream has been declared, print, println and printf can be used to write data to the text file.  To write to the file on a specified directory,  PrintWriter outputStream = new PrintWriter(new FileOutputStream("d:/sample/data.txt"));  To append to a text file  To write to the end of the file,  PrintWriter outputStream = new PrintWriter(new FileOutputStream("d:/sample/data.txt", true));
  • 7. Exercise Write a program to store the exchange rate to the text file named currency.txt USD 0.245 EUR 0.205 GBP 0.184 AUD 0.332 THB 7.41
  • 8. Reading from Text File  Two most common stream classes used for reading text file are the Scanner class and BufferReader class.  Scanner streamObject = new Scanner (new FileInputStream(FileName));  Close the file after finish reading using streamObject.close() method.  The FileInputStream and FileNotFoundException class need to be loaded using the import statement.
  • 9. Reading from Text File import java.util.Scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; try { Scanner inputStream = new Scanner(new FileInputStream("data.txt")); … inputStream.close(); } catch (FileNotFoundException e) { System.out.println("File was not found"); }
  • 10. Reading from Text File  After the inputStream has been declared, nextInt, nextDouble, nextLine can be used to read data from the text file. String input = inputStream.nextLine(); int num1 = inputStream.nextInt(); double num2 = inputStream.nextDouble();  To check for the end of a text file  while (inputStream.hasNextLine())  To open file from a specified directory  Scanner inputStream = new Scanner(new FileInputStream("d:/sample/data.txt"));
  • 11. Reading from Text File  BufferedReader class is another class that can read text from the text file.  BufferedReader inputStream = new BufferedReader( new FileReader(FileName));  Close the file after finish reading using streamObject.close() method.  The BufferedReader, FileReader and FileNotFoundException, IOException class need to be loaded using the import statement.
  • 12. Reading from Text File import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; try { BufferedReader inputStream = new BufferedReader (new FileReader("data.txt")); … inputStream.close(); } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println(“Error reading from file"); }
  • 13. Reading from Text File  After the inputStream has been declared, read and readLine can be used to read data from the text file. String input = inputStream.readLine();  To check for the end of a text file  while ( (input=inputStream.readLine()) != null)  To open file from a specified directory  BufferedReader inputStream = new BufferedReader( new FileReader("d:/sample/data.txt"));
  • 14. Example Write a program to read the exchange rate from currency.txt and compute the exchange rate
  • 15. File Class  File class contains methods that used to check the properties of the file.  The file class is loaded using import java.io.File; File fileObject = new File("data.txt"); if (fileObject.exists()) { System.out.println("The file is already exists"); fileObject.renameTo("data1.txt"); } if (fileObject.canRead()) System.out.println("The file is readable"); if (fileObject.canWrite()) System.out.println("The file is writable");
  • 16. Writing to Binary File  ObjectOutputStream is the stream class that used to write data to a binary file.  ObjectOutputStream streamObject = new ObjectOutputStream (new FileOutputStream(FileName));  The ObjectOutputStream, FileOutputStream and IOException class need to be loaded using the import statement.  The writeInt, writeDouble, writeChar, writeBoolean can be used to write the value of different variable type to the output stream. Use writeUTF to write String object to the output stream.  Close the file after finish writing using streamObject.close() method.
  • 17. Writing to Binary File import java.io.IOException; import java.io.ObjectOutputStream; import java.io.FileOutputStream; try { ObjectOutputStream outputStream = new ObjectOutputStream (new FileOutputStream("data.dat")); … outputStream.close(); } catch (IOException e) { System.out.println("Problem with file output."); }
  • 18. Reading from Binary File  ObjectInputStream is the stream class that used to read a binary file written using ObjectOutputStream  ObjectInputStream streamObject = new ObjectInputStream (new FileInputStream(FileName));  The ObjectInputStream, FileInputStream and IOException, FileNotFoundException class need to be loaded using the import statement.  The readInt, readDouble, readChar, readBoolean can be used to read the value from the input stream. Use readUTF to read String object from the input stream.  Close the file after finish writing using streamObject.close() method.
  • 19. Reading from Binary File import java.io.IOException; import java.io.FileNotFoundException; import java.io.ObjectInputStream; import java.io.FileOutputStream; try { ObjectInputStream inputStream = new ObjectInputStream (new FileInputStream("data.dat")); … inputStream.close(); } catch (FileNotFoundException e) { System.out.println("File was not found"); } catch (IOException e) { System.out.println("Problem with file input."); }
  • 20. Reading from Binary File  To check for the end of a text file  Use EOFException try { while(true) { number = inputStream.readInt(); } } catch (EOFException e) { }
  • 21. Exercise  Generate N random numbers within 10-100, N is within (20-30) and then store in a binary file number.dat.  Read all the random numbers from number.dat  Display all the numbers, N, maximum and minimum