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

PPT
Chapter 12 - File Input and Output
Eduardo Bergavera
 
PPT
Java căn báșŁn - Chapter12
Vince Vo
 
PDF
Java IO Stream, the introduction to Streams
ranganadh6
 
PPTX
Chapter 10.3
sotlsoc
 
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPT
File Input & Output
PRN USM
 
PPTX
Input output files in java
Kavitha713564
 
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Java căn báșŁn - Chapter12
Vince Vo
 
Java IO Stream, the introduction to Streams
ranganadh6
 
Chapter 10.3
sotlsoc
 
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Java I/o streams
Hamid Ghorbani
 
File Input & Output
PRN USM
 
Input output files in java
Kavitha713564
 

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

PDF
Create a text file named lnfo.txt. Enter the following informatio.pdf
shahidqamar17
 
PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PPSX
Stream
BRIJESH SRIVASTAVA
 
DOCX
Write a java program that allows the user to input the name of a file.docx
noreendchesterton753
 
DOCX
Write a java program that allows the user to input the name of a fil.docx
ajoy21
 
PPTX
File Handling.pptx
PragatiSutar4
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPTX
Understanding java streams
Shahjahan Samoon
 
PPTX
Java file
sonnetdp
 
DOCX
FileHandling.docx
NavneetSheoran3
 
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
PDF
26 io -ii file handling
Ravindra Rathore
 
PPTX
File Input and output.pptx
cherryreddygannu
 
PPTX
Java
Dhruv Sabalpara
 
PDF
Please include comments if at all possible Use a socket connection t.pdf
fashionfootwear1
 
PPTX
Basic of Javaio
suraj pandey
 
PPT
Java IO Streams V4
Sunil OS
 
PDF
Input File dalam C++
Teguh Nugraha
 
PDF
Lecture 11.pdf
SakhilejasonMsibi
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
shahidqamar17
 
File Handling in Java.pdf
SudhanshiBakre1
 
Write a java program that allows the user to input the name of a file.docx
noreendchesterton753
 
Write a java program that allows the user to input the name of a fil.docx
ajoy21
 
File Handling.pptx
PragatiSutar4
 
Java Input Output and File Handling
Sunil OS
 
Understanding java streams
Shahjahan Samoon
 
Java file
sonnetdp
 
FileHandling.docx
NavneetSheoran3
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
26 io -ii file handling
Ravindra Rathore
 
File Input and output.pptx
cherryreddygannu
 
Please include comments if at all possible Use a socket connection t.pdf
fashionfootwear1
 
Basic of Javaio
suraj pandey
 
Java IO Streams V4
Sunil OS
 
Input File dalam C++
Teguh Nugraha
 
Lecture 11.pdf
SakhilejasonMsibi
 
Ad

Recently uploaded (20)

PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PPTX
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
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