SlideShare a Scribd company logo
File
Handling
in Java
Table of contents
01 02
File File Handling
03
Streams
04
File Class
05
File Reading
06
File Writing
File
01
What is a File?
What is a File?
text, images, videos, programs, and more
Types of Files
Content
Attributes
size, type, creation date, modification
date, permissions, etc.
text files, binary files, executable files,
configuration files, etc
Named collection of related information
stored on a storage medium, typically a disk
</>
File
Handling
02
What is File Handling?
 Managing files in a computer system.
 Involves reading, writing, creating, deleting, and modifying
files.
Accessing files for read/write
Writing
Opening
Reading
Retrieving data from files
Storing data into files
Closing
Ending file access
Streams
03
What are Streams?
 Represent a sequence of data elements from a source
- I/O Channels, Arrays, ArrayLists, etc.
 Do not store data; they are pipelines through which data flows.
 Java views files as sequential streams of bytes.
 End of a file is determined by EOF (End-of-File) marker.
 File streams can handle data as
− bytes
− characters
File Streams
Byte-Based and Character-Based Streams
File streams can handle data as bytes or characters
Character Streams
File Streams
Byte Steams
• deal with binary data
• used for binary files
 value 5 stored in binary
format of the numeric
value 5, e.g., 0000101
• handle data as a sequence
of characters
• used for text files
• value 5 stored in binary
format of the character
value 5, e.g., 00000000
00110101, represents Unicode
of ‘5’
Examples of File Streams
Some Examples (Classes) are
Character Streams
Byte Streams
• FileInputStream
• FileOutputStream
• FileReader
• FileWriter
• BufferedReader
• BufferedWriter
Standard Streams
 Java programs associate streams with devices.
 Actually, an object of standard streams is created and
associated with devices
enables a program to input
bytes from the keyboard
System.out (standard
output stream)
System.in (standard
input stream)
enables a program to output
character data to the screen
System.err (standard
error stream)
enables a program to output character-
based error messages to the screen
File Class
04
The File Class
 An abstract representation of file and directory
pathnames
 Part of the java.io package
 Allows operations such as
• obtaining properties
• renaming
• deleting
• creating directories or files
 Provides certain methods for performing operations, like
.delete(), .createNewFile(), .getName()
Pathnames
 pathname strings used to name files and directories.
 First name in an abstract pathname is a directory name.
 Each subsequent name in an abstract pathname
denotes a directory; the last name may denote either a
directory or a file
 e.g., C:UsersHassanDocumentsfile.txt
 Pathname is either absolute or relative
Relative Pathname
 A relative pathname specifies the path relative to the current
working directory.
 e.g., pathname is ‘file.txt’
 We’re are working in C:UsersUsernameDocuments
 file.txt is the relative path to our directory
Absolute Pathname
 An absolute pathname specifies the full path starting from the
root directory.
 e.g., ‘C:UsersUsernameDocumentsfile.txt’
File Class Methods
Name
Return
Type
Description
File(pathname:
String)
File
Creates a File object for the specified path name.
The path name may be a directory or a file.
canRead() Boolean Returns true if the file exists and can be read.
createNewFile() Boolean Creates a new empty file.
canWrite() Boolean Returns true if the file exists and can be written.
exists() Boolean Returns true if the file or the directory exists.
delete() Boolean Deletes the file.
getName() String
Returns the last name of the complete directory and
file name.
getAbsolutePath() String Returns the complete absolute file or directory name
length() Long
Returns the size of the file, or 0 if it does not exist or if
it is a directory.
File Class Methods
Name
Return
Type
Description
isDirectory() boolean Returns true if the File object represents a directory.
isFile() boolean Returns true if the File object represents a file.
isAbsolute() boolean
Returns true if the File object is created using an
absolute path name.
isHidden() boolean
Returns true if the file represented in the File object is
hidden.
lastModified() long Returns the time that the file was last modified.
renameTo(dest:
File)
boolean
Renames the file or directory represented by this File
object to the specified name represented in dest.
The method returns true if the operation succeeds.
list() String[] Retrieves an array of files available in the directory.
mkdir() Boolean Creates a new directory.
Code
Examples
Code:
import java.io.File;
public class FileClass {
public static void main(String[] args) {
// Create a File object
File file = new File("D:Other DataSeasons.txt");
// Check if is a file
System.out.println("Is it a file?: " + file.isFile());
// Check if file can be read and written
System.out.println("Can read file: " + file.canRead());
System.out.println("Can write to file: " + file.canWrite());
// Check if file exists
System.out.println("File exists: " + file.exists());
// Get file name and absolute path
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
}
}
Output:
Code:
import java.io.File;
public class FileClass {
public static void main(String[] args) {
// Create a File object
File file = new File("D:Other DataSeasons.txt");
// Get file length
System.out.println("File length (in bytes): " + file.length());
// Check if it's a directory and if it's an absolute path
System.out.println("Is directory: " + file.isDirectory());
System.out.println("Is absolute path: " + file.isAbsolute());
// Get file path, last modified time, and rename the file
System.out.println("File path: " + file.getPath());
System.out.println("Last modified: " + file.lastModified());
}
}
Output:
Rename and Delete:
import java.io.File;
public class FileClass {
public static void main(String[] args) {
File file = new File("D:Other DataSeasons.txt");
// rename the file
String newName = "Unwatched Seasons.txt";
File newFile = new File(file.getParent(), newName);
if (file.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
} // Deleting the file
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}
Output:
Create a File:
import java.io.File;
import java.io.IOException;
public class FileClass {
public static void main(String[] args) {
File file = new File("D:Other DataSeasons.txt");
try {
// Creating a new file
if (file.createNewFile()) {
System.out.println("File created successfully at: " +
file.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
}
Output:
File
Reading
05
What is File Reading?
 Process of retrieving data stored in a file on a storage device
and bringing that data into your program's memory for further
processing or manipulation.
 Reading from a file involves:
Open File:
Specify file path and permissions.
Access Content:
Read Line by Line (for text files).
Read Blocks or Chunks (for larger files).
Read All at Once (for smaller files).
Process Data:
Manipulate or analyze the read data.
Close File:
Release system resources
Classes for File Reading
Some Examples (Classes) are
Character Streams
Byte Streams
• FileInputStream
• FileReader
• BufferedReader
Scanner
FileReader
int letters;
FileReader reader = null;
try {
reader = new FileReader("fileName"))
// .ready() tells whether the stream is ready to read
while (reader.ready()) {
// .read() reads characters and stores as Unicode values
letters = reader.read();
System.out.print((char) letters);
} }
catch(IOException e) {
System.out.println(e.toString());;
}
finally {
reader.close();
}
Import from java.io package, before using
Output:
Limitations of FileInputStream
 Primarily for reading bytes, lacking higher-level
functionalities.
 Doesn't handle character encoding automatically
 Must be used with InputStreamReader class and
Character-set must be specified.
 No built-in method for reading lines of text
 Absence of direct EOF (end-of-file) checking methods
Limitations of FileReader
 Slower performance when reading larger files due to
character-by-character reading
 Requires additional handling for reading lines by combining
with other classes.
BufferedReader
 Reads data from a character-input stream efficiently by
buffering characters, reducing the number of I/O
operations and improving performance.
 Provides readLine(), for reading lines of text from an input
stream, returning null when the end of the stream is
reached.
Limitations:
 Lacks built-in methods for directly reading specific data
types; manual parsing is needed.
 Primarily designed for reading text; not optimized for
reading binary data.
Code:
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader("D:Seasons.txt"))
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
reader.close();
}
First import it before using from java.io package
Output:
Scanner
 Provides a simple way to read and parse primitive types
and strings from various input sources like files, streams, or
strings.
 Has methods like nextInt(), nextDouble(), nextLine(), etc.,
to read integers, doubles, strings, etc., from the input source
 Import Scanner from java.util package before using
Limitations:
 For large files or complex parsing requirements, Scanner
might not be as efficient as BufferedReader
 Might throw exceptions if the input doesn't match the
expected data type, requiring additional error handling
Reading Integer:
int number;
Scanner input = null;
try {
input = new Scanner(new File("D:Numbers.txt"));
// .hasNextInt() tells whether next is integer
while (input.hasNextInt()) {
number = input.nextInt();
System.out.println(number);
}
}
catch(FileNotFoundException e) {
System.out.println(e.toString());;
}
finally {
input.close();
}
Output:
Reading Double:
double number1;
Scanner input = null;
try {
input = new Scanner(new File("D:doubleNumbers.txt"));
while (input.hasNextDouble()) {
number1 = input.nextDouble();
System.out.println(number1);
}
}
catch(FileNotFoundException e) {
System.out.println(e.toString());;
}
}
finally {
input.close();
}
Output:
Reading Line:
String line;
Scanner input = null;
try {
input = new Scanner(new File("D:Seasons.txt"));
while (input.hasNextLine()) {
line = input.nextLine();
System.out.println(line);
}
}
catch(FileNotFoundException e) {
System.out.println(e.toString());;
}
finally {
input.close();
}
Output:
File
Writing
06
What is File Writing?
 Process of creating, opening, and manipulating files to save
data or information onto a storage device.
 Allows to make data available even after the program finishes.
 Writing to a file involves:
Open File:
Specify file path and permissions, e.g., File class.
Access Content:
Read Line by Line, Blocks or Chunks, All at Once.
Process Data:
Manipulate or analyze the read data.
Write Data:
Write data using classes.
Close File:
Release system resources
Classes for File Reading
Some Examples (Classes) are
Character Streams
Byte Streams
• FileOutputStream
• FileWriter
• BufferedWriter
• PrintWriter
File Writer
 Powerful tool for writing character-based data to files
 Designed to work with text files containing letters,
punctuation, and other standard characters.
 Offers methods like write, write(char ch), write(char[]
charArr), write(String str),to write characters, arrays of
characters, strings.
 Uses an internal buffer to store data efficiently before
writing it to the file.
 One can flush the buffer manually using flush() to ensure
data is written immediately
 Import FileWriter from java.io package before using
Limitations of FileOutputStream
 Used for writing raw bytes of data to a file.
 Doesn't provide methods for handling textual data directly.
 Doesn't buffer data, which leads to frequent disk writes,
impacting performance with small writes
Limitations of FileWriter
 Used for writing characters, strings, char arrays to a file
 Not optimized for handling large amounts of data efficiently
Writing Line/String:
String content = "Some content to write into file.";
FileWriter writer = null;
try {
writer = new FileWriter("output.txt");
writer.write(content);
writer.flush();
System.out.println("Content has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing.");
e.printStackTrace();
} finally {
writer.close();
}
Output:
Writing Characters
String content = "Writing Characters to File";
FileWriter writer = null;
try {
writer = new FileWriter("output1.txt");
for (int i = 0; i < content.length(); i++){
writer.write(content.charAt(i));
}
System.out.println("Content has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
} finally {
writer.close();
}
Output:
Writing Character Array
FileWriter writer = null;
try {
char[] charArray = { 'J', 'a', 'v', 'a', '-', '2', '1' };
writer = new FileWriter("output2.txt");
writer.write(charArray);
writer.flush();
System.out.println("Content has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file." + "n" + e.toString());
} finally {
writer.close();
}
Output:
Buffered Writer
 Powerful tool for writing text to files more efficiently than the
basic FileWriter.
 Works by buffering data in memory before writing it to the
underlying file stream.
 This can significantly improve performance, especially
when dealing with small files or frequent writes.
 Offers methods like write, write(char ch), write(char[]
charArr), write(String str),to write characters, arrays of
characters, strings.
 One can flush the buffer manually using flush() to ensure
data is written immediately
 Import BufferedWriter from java.io package before using
Writing String/ Lines:
String data = "Writing using buffered Writer";
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("myfile.txt"));
writer.write(data);
writer.flush();
System.out.println("Content has been written to the
file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file." + "n" + e.toString());
} finally {
writer.close();
}
Output:
 Same syntax and procedure as that of FileWriter.
 Use these write(char ch), write(char[] charArr).
Writing Character and Char Array:
When to use BufferedWriter?
Consider using BufferedWriter whenever you need to:
 Write large amounts of character data to files.
 Improve the performance of file writes, especially for small
files or frequent writes.
 Enhance the stability and reliability of your file handling
PrintWriter
 Writes formatted text to a file or any output stream.
 Part of the java.io package.
 Handles automatic buffering and flushing, providing
smoother and more efficient output.
 Provides simple methods like print(), println(), and printf()
for various data types, streamlining text output.
 Allows specifying the character encoding (e.g., UTF-8) for
consistent handling of different language characters.
 Uses format specifiers (%d, %s, etc.) to format data before
writing, allowing for custom output formats
Using print()/println():
PrintWriter writer = null;
try {
writer = new PrintWriter("output.txt");
writer.println("This is PrintWriter on Java, ver:" + 21);
System.out.println("Content has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file." + "n" + e.toString());
} finally {
writer.close();
}
 .print() writes the data to the file as it is
 .println() adds newline after writing
Output:
Formatted Writing:
int age = 20;
String name = "Hassan";
PrintWriter writer = null;
try {
writer = new PrintWriter("output1.txt");
writer.printf("Name: %s, Age: %dn", name, age);
System.out.println("Content has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file." + "n" + e.toString());
} finally {
writer.close();
}
 Can be achieved by printf()
 Custom formatting is passed as argument to method
 Format specifiers are also used.
Output:
try-with-resources
 Introduced in Java 7 that simplifies resource management.
 Ensures resources are automatically closed regardless of
whether your code completes normally or throws an
exception.
Working and Usage
 Within the parentheses after try, you can create resource
variables representing objects that need to be closed.
 The code block in try, can use the declared resources like
any other variable.
 Once the block exits, regardless of the reason (normal
execution or exception), all resources are automatically
closed in the reverse order of their declaration.
Syntax:
try (ResourceType1 resource1 = /* initialization */;
ResourceType2 resource2 = /* initialization */ ;
// ... add more resources as needed
ResourceTypeN resourceN = /* initialization */) {
// Your code that uses the resources declared above
} catch (Exception1 exception1) {
// Handle exception1 thrown by your code or resources
} catch (ExceptionN exceptionN) {
// ….Handle exceptionN thrown by your code or resources
}
Example Code:
int age = 20;
String name = "Hassan";
try (PrintWriter writer = new PrintWriter("output.txt")){
writer.printf("Name: %s, Age: %dn", name, age);
System.out.println("Content has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file." + "n" + e.toString());
}
 Formatted writing code realized using try-with-
resources
Output:

More Related Content

Similar to File Handlingb in java. A brief presentation on file handling

Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
sotlsoc
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
Mahmoud Ouf
 
Files nts
Files ntsFiles nts
Files nts
kalyani66
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
Mahmoud Ouf
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
JAVA
JAVAJAVA
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)
It Academy
 
File Handling
File HandlingFile Handling
File Handling
TusharBatra27
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.ppt
HelalMirzad
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System Interface
Wayne Jones Jnr
 
Ch10
Ch10Ch10
File system interface
File system interfaceFile system interface
File system interface
Dayan Ahmed
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
Sisir Ghosh
 

Similar to File Handlingb in java. A brief presentation on file handling (20)

Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Files nts
Files ntsFiles nts
Files nts
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Data file handling
Data file handlingData file handling
Data file handling
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
JAVA
JAVAJAVA
JAVA
 
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)
 
File Handling
File HandlingFile Handling
File Handling
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.ppt
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System Interface
 
Ch10
Ch10Ch10
Ch10
 
File system interface
File system interfaceFile system interface
File system interface
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
 

Recently uploaded

How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 

Recently uploaded (20)

How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 

File Handlingb in java. A brief presentation on file handling

  • 2. Table of contents 01 02 File File Handling 03 Streams 04 File Class 05 File Reading 06 File Writing
  • 4. What is a File? text, images, videos, programs, and more Types of Files Content Attributes size, type, creation date, modification date, permissions, etc. text files, binary files, executable files, configuration files, etc Named collection of related information stored on a storage medium, typically a disk </>
  • 6. What is File Handling?  Managing files in a computer system.  Involves reading, writing, creating, deleting, and modifying files. Accessing files for read/write Writing Opening Reading Retrieving data from files Storing data into files Closing Ending file access
  • 8. What are Streams?  Represent a sequence of data elements from a source - I/O Channels, Arrays, ArrayLists, etc.  Do not store data; they are pipelines through which data flows.  Java views files as sequential streams of bytes.  End of a file is determined by EOF (End-of-File) marker.  File streams can handle data as − bytes − characters File Streams
  • 9. Byte-Based and Character-Based Streams File streams can handle data as bytes or characters Character Streams File Streams Byte Steams • deal with binary data • used for binary files  value 5 stored in binary format of the numeric value 5, e.g., 0000101 • handle data as a sequence of characters • used for text files • value 5 stored in binary format of the character value 5, e.g., 00000000 00110101, represents Unicode of ‘5’
  • 10. Examples of File Streams Some Examples (Classes) are Character Streams Byte Streams • FileInputStream • FileOutputStream • FileReader • FileWriter • BufferedReader • BufferedWriter
  • 11. Standard Streams  Java programs associate streams with devices.  Actually, an object of standard streams is created and associated with devices enables a program to input bytes from the keyboard System.out (standard output stream) System.in (standard input stream) enables a program to output character data to the screen System.err (standard error stream) enables a program to output character- based error messages to the screen
  • 13. The File Class  An abstract representation of file and directory pathnames  Part of the java.io package  Allows operations such as • obtaining properties • renaming • deleting • creating directories or files  Provides certain methods for performing operations, like .delete(), .createNewFile(), .getName()
  • 14. Pathnames  pathname strings used to name files and directories.  First name in an abstract pathname is a directory name.  Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file  e.g., C:UsersHassanDocumentsfile.txt  Pathname is either absolute or relative
  • 15. Relative Pathname  A relative pathname specifies the path relative to the current working directory.  e.g., pathname is ‘file.txt’  We’re are working in C:UsersUsernameDocuments  file.txt is the relative path to our directory Absolute Pathname  An absolute pathname specifies the full path starting from the root directory.  e.g., ‘C:UsersUsernameDocumentsfile.txt’
  • 16. File Class Methods Name Return Type Description File(pathname: String) File Creates a File object for the specified path name. The path name may be a directory or a file. canRead() Boolean Returns true if the file exists and can be read. createNewFile() Boolean Creates a new empty file. canWrite() Boolean Returns true if the file exists and can be written. exists() Boolean Returns true if the file or the directory exists. delete() Boolean Deletes the file. getName() String Returns the last name of the complete directory and file name. getAbsolutePath() String Returns the complete absolute file or directory name length() Long Returns the size of the file, or 0 if it does not exist or if it is a directory.
  • 17. File Class Methods Name Return Type Description isDirectory() boolean Returns true if the File object represents a directory. isFile() boolean Returns true if the File object represents a file. isAbsolute() boolean Returns true if the File object is created using an absolute path name. isHidden() boolean Returns true if the file represented in the File object is hidden. lastModified() long Returns the time that the file was last modified. renameTo(dest: File) boolean Renames the file or directory represented by this File object to the specified name represented in dest. The method returns true if the operation succeeds. list() String[] Retrieves an array of files available in the directory. mkdir() Boolean Creates a new directory.
  • 19. Code: import java.io.File; public class FileClass { public static void main(String[] args) { // Create a File object File file = new File("D:Other DataSeasons.txt"); // Check if is a file System.out.println("Is it a file?: " + file.isFile()); // Check if file can be read and written System.out.println("Can read file: " + file.canRead()); System.out.println("Can write to file: " + file.canWrite()); // Check if file exists System.out.println("File exists: " + file.exists()); // Get file name and absolute path System.out.println("File name: " + file.getName()); System.out.println("Absolute path: " + file.getAbsolutePath()); } }
  • 21. Code: import java.io.File; public class FileClass { public static void main(String[] args) { // Create a File object File file = new File("D:Other DataSeasons.txt"); // Get file length System.out.println("File length (in bytes): " + file.length()); // Check if it's a directory and if it's an absolute path System.out.println("Is directory: " + file.isDirectory()); System.out.println("Is absolute path: " + file.isAbsolute()); // Get file path, last modified time, and rename the file System.out.println("File path: " + file.getPath()); System.out.println("Last modified: " + file.lastModified()); } }
  • 23. Rename and Delete: import java.io.File; public class FileClass { public static void main(String[] args) { File file = new File("D:Other DataSeasons.txt"); // rename the file String newName = "Unwatched Seasons.txt"; File newFile = new File(file.getParent(), newName); if (file.renameTo(newFile)) { System.out.println("File renamed successfully."); } else { System.out.println("Failed to rename the file."); } // Deleting the file if (file.delete()) { System.out.println("File deleted successfully."); } else { System.out.println("Failed to delete the file."); } } }
  • 25. Create a File: import java.io.File; import java.io.IOException; public class FileClass { public static void main(String[] args) { File file = new File("D:Other DataSeasons.txt"); try { // Creating a new file if (file.createNewFile()) { System.out.println("File created successfully at: " + file.getAbsolutePath()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred while creating the file."); e.printStackTrace(); } } }
  • 28. What is File Reading?  Process of retrieving data stored in a file on a storage device and bringing that data into your program's memory for further processing or manipulation.  Reading from a file involves: Open File: Specify file path and permissions. Access Content: Read Line by Line (for text files). Read Blocks or Chunks (for larger files). Read All at Once (for smaller files). Process Data: Manipulate or analyze the read data. Close File: Release system resources
  • 29. Classes for File Reading Some Examples (Classes) are Character Streams Byte Streams • FileInputStream • FileReader • BufferedReader Scanner
  • 30. FileReader int letters; FileReader reader = null; try { reader = new FileReader("fileName")) // .ready() tells whether the stream is ready to read while (reader.ready()) { // .read() reads characters and stores as Unicode values letters = reader.read(); System.out.print((char) letters); } } catch(IOException e) { System.out.println(e.toString());; } finally { reader.close(); } Import from java.io package, before using
  • 32. Limitations of FileInputStream  Primarily for reading bytes, lacking higher-level functionalities.  Doesn't handle character encoding automatically  Must be used with InputStreamReader class and Character-set must be specified.  No built-in method for reading lines of text  Absence of direct EOF (end-of-file) checking methods Limitations of FileReader  Slower performance when reading larger files due to character-by-character reading  Requires additional handling for reading lines by combining with other classes.
  • 33. BufferedReader  Reads data from a character-input stream efficiently by buffering characters, reducing the number of I/O operations and improving performance.  Provides readLine(), for reading lines of text from an input stream, returning null when the end of the stream is reached. Limitations:  Lacks built-in methods for directly reading specific data types; manual parsing is needed.  Primarily designed for reading text; not optimized for reading binary data.
  • 34. Code: BufferedReader reader = null; try { reader = new BufferedReader (new FileReader("D:Seasons.txt")) String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { reader.close(); } First import it before using from java.io package
  • 36. Scanner  Provides a simple way to read and parse primitive types and strings from various input sources like files, streams, or strings.  Has methods like nextInt(), nextDouble(), nextLine(), etc., to read integers, doubles, strings, etc., from the input source  Import Scanner from java.util package before using Limitations:  For large files or complex parsing requirements, Scanner might not be as efficient as BufferedReader  Might throw exceptions if the input doesn't match the expected data type, requiring additional error handling
  • 37. Reading Integer: int number; Scanner input = null; try { input = new Scanner(new File("D:Numbers.txt")); // .hasNextInt() tells whether next is integer while (input.hasNextInt()) { number = input.nextInt(); System.out.println(number); } } catch(FileNotFoundException e) { System.out.println(e.toString());; } finally { input.close(); }
  • 39. Reading Double: double number1; Scanner input = null; try { input = new Scanner(new File("D:doubleNumbers.txt")); while (input.hasNextDouble()) { number1 = input.nextDouble(); System.out.println(number1); } } catch(FileNotFoundException e) { System.out.println(e.toString());; } } finally { input.close(); }
  • 41. Reading Line: String line; Scanner input = null; try { input = new Scanner(new File("D:Seasons.txt")); while (input.hasNextLine()) { line = input.nextLine(); System.out.println(line); } } catch(FileNotFoundException e) { System.out.println(e.toString());; } finally { input.close(); }
  • 44. What is File Writing?  Process of creating, opening, and manipulating files to save data or information onto a storage device.  Allows to make data available even after the program finishes.  Writing to a file involves: Open File: Specify file path and permissions, e.g., File class. Access Content: Read Line by Line, Blocks or Chunks, All at Once. Process Data: Manipulate or analyze the read data. Write Data: Write data using classes. Close File: Release system resources
  • 45. Classes for File Reading Some Examples (Classes) are Character Streams Byte Streams • FileOutputStream • FileWriter • BufferedWriter • PrintWriter
  • 46. File Writer  Powerful tool for writing character-based data to files  Designed to work with text files containing letters, punctuation, and other standard characters.  Offers methods like write, write(char ch), write(char[] charArr), write(String str),to write characters, arrays of characters, strings.  Uses an internal buffer to store data efficiently before writing it to the file.  One can flush the buffer manually using flush() to ensure data is written immediately  Import FileWriter from java.io package before using
  • 47. Limitations of FileOutputStream  Used for writing raw bytes of data to a file.  Doesn't provide methods for handling textual data directly.  Doesn't buffer data, which leads to frequent disk writes, impacting performance with small writes Limitations of FileWriter  Used for writing characters, strings, char arrays to a file  Not optimized for handling large amounts of data efficiently
  • 48. Writing Line/String: String content = "Some content to write into file."; FileWriter writer = null; try { writer = new FileWriter("output.txt"); writer.write(content); writer.flush(); System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing."); e.printStackTrace(); } finally { writer.close(); }
  • 50. Writing Characters String content = "Writing Characters to File"; FileWriter writer = null; try { writer = new FileWriter("output1.txt"); for (int i = 0; i < content.length(); i++){ writer.write(content.charAt(i)); } System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing to the file."); e.printStackTrace(); } finally { writer.close(); }
  • 52. Writing Character Array FileWriter writer = null; try { char[] charArray = { 'J', 'a', 'v', 'a', '-', '2', '1' }; writer = new FileWriter("output2.txt"); writer.write(charArray); writer.flush(); System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing to the file." + "n" + e.toString()); } finally { writer.close(); }
  • 54. Buffered Writer  Powerful tool for writing text to files more efficiently than the basic FileWriter.  Works by buffering data in memory before writing it to the underlying file stream.  This can significantly improve performance, especially when dealing with small files or frequent writes.  Offers methods like write, write(char ch), write(char[] charArr), write(String str),to write characters, arrays of characters, strings.  One can flush the buffer manually using flush() to ensure data is written immediately  Import BufferedWriter from java.io package before using
  • 55. Writing String/ Lines: String data = "Writing using buffered Writer"; BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter("myfile.txt")); writer.write(data); writer.flush(); System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing to the file." + "n" + e.toString()); } finally { writer.close(); }
  • 57.  Same syntax and procedure as that of FileWriter.  Use these write(char ch), write(char[] charArr). Writing Character and Char Array: When to use BufferedWriter? Consider using BufferedWriter whenever you need to:  Write large amounts of character data to files.  Improve the performance of file writes, especially for small files or frequent writes.  Enhance the stability and reliability of your file handling
  • 58. PrintWriter  Writes formatted text to a file or any output stream.  Part of the java.io package.  Handles automatic buffering and flushing, providing smoother and more efficient output.  Provides simple methods like print(), println(), and printf() for various data types, streamlining text output.  Allows specifying the character encoding (e.g., UTF-8) for consistent handling of different language characters.  Uses format specifiers (%d, %s, etc.) to format data before writing, allowing for custom output formats
  • 59. Using print()/println(): PrintWriter writer = null; try { writer = new PrintWriter("output.txt"); writer.println("This is PrintWriter on Java, ver:" + 21); System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing to the file." + "n" + e.toString()); } finally { writer.close(); }  .print() writes the data to the file as it is  .println() adds newline after writing
  • 61. Formatted Writing: int age = 20; String name = "Hassan"; PrintWriter writer = null; try { writer = new PrintWriter("output1.txt"); writer.printf("Name: %s, Age: %dn", name, age); System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing to the file." + "n" + e.toString()); } finally { writer.close(); }  Can be achieved by printf()  Custom formatting is passed as argument to method  Format specifiers are also used.
  • 63. try-with-resources  Introduced in Java 7 that simplifies resource management.  Ensures resources are automatically closed regardless of whether your code completes normally or throws an exception. Working and Usage  Within the parentheses after try, you can create resource variables representing objects that need to be closed.  The code block in try, can use the declared resources like any other variable.  Once the block exits, regardless of the reason (normal execution or exception), all resources are automatically closed in the reverse order of their declaration.
  • 64. Syntax: try (ResourceType1 resource1 = /* initialization */; ResourceType2 resource2 = /* initialization */ ; // ... add more resources as needed ResourceTypeN resourceN = /* initialization */) { // Your code that uses the resources declared above } catch (Exception1 exception1) { // Handle exception1 thrown by your code or resources } catch (ExceptionN exceptionN) { // ….Handle exceptionN thrown by your code or resources }
  • 65. Example Code: int age = 20; String name = "Hassan"; try (PrintWriter writer = new PrintWriter("output.txt")){ writer.printf("Name: %s, Age: %dn", name, age); System.out.println("Content has been written to the file."); } catch (IOException e) { System.out.println("An error occurred while writing to the file." + "n" + e.toString()); }  Formatted writing code realized using try-with- resources