SlideShare a Scribd company logo
1 of 11
Dr.Ranjitha M
Department of Computer Science[PG]
Kristu Jayanti College, Bengaluru
1
Kristu Jayanti College
Files and operations in Java
2
Kristu Jayanti College
java.io package
• java.io package contains almost every class you need to perform
input and output (I/O) in Java.
• Java programs perform I/O through streams.
• A stream is an abstraction that either produces or consumes
information.
• A stream is linked to a physical device by the Java I/O system.
• All streams behave in the same manner, even if the actual physical
devices to which they are linked differ.
3
Kristu Jayanti College
java.io package
• Same I/O classes and methods can be applied to different types of
devices.
• input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket.
• Streams are a clean way to deal with input/ output without having
every part of your code understand the difference between a
keyboard and a network.
4
Kristu Jayanti College
File operations
• Two of the most often-used stream classes are FileInputStream and
FileOutputStream
• Toopen a file, you simply create an object of one of these classes,
specifying the name of the file as an argument to the constructor.
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws
FileNotFoundException
• FileNotFoundException is a subclass of IOException.
• When an output file is opened, any preexisting file by the same name
is destroyed.
5
Kristu Jayanti College
File operations
• When you are done with a file, you must close it.
• This is done by calling the close( ) method, which is implemented by
both FileInputStream and FileOutputStream.
void close( ) throws IOException
• Closing a file releases the system resources allocated to the file,
allowing them to be used by another file.
• Failure to close a file can result in “memory leaks” because of unused
resources remaining allocated.
6
Kristu Jayanti College
File operations
• Toread from a file, you can use a version of read( ) that is defined
within FileInputStream.
int read( ) throws IOException
• Each time that it is called, it reads a single byte from the file and
returns the byte as an integer value.
• read( ) returns –1 when the end of the file is encountered.
• It can throw an IOException.
7
Kristu Jayanti College
File operation in Java
import java.io.*;
class ShowFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;
if(args.length != 1) {// First, confirm that a filename has been specified.
System.out.println("Usage: ShowFile filename");
return;
}
try { // Attempt to open the file.
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return;
}
// At this point, the file is open and can be read.
try { // The following reads characters until EOF is encountered.
do {
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
}
try { // Close the file
fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
8
Kristu Jayanti College
File operation in Java
import java.io.*;
class ShowFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin = null;
if(args.length != 1) {// First, confirm that a filename has been specified.
System.out.println("Usage: ShowFile filename");
return;
}
try { // Attempt to open the file.
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
}
catch(FileNotFoundException e)
{ System.out.println("Cannot Open File");
return;
} catch(IOException e) {
System.out.println("Error Reading File");
}
finally {
// Close file in allcases.
try {
if(fin != null) fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}// End finally
}//End main
}//End class
9
Kristu Jayanti College
File operations
• Towrite to a file, you can use the write( ) method defined by
FileOutputStream.
void write(int byteval) throws IOException
• This method writes the byte specified by byteval to the file.
• Although byteval is declared as an integer, only the low-order eight
bits are written to the file.
• If an error occurs during writing, an IOException is thrown.
1
0
Kristu Jayanti College
File operation in Java
import java.io.*; class
CopyFile {
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin = null;
FileOutputStream fout = null;
// First, confirm that both files have been specified.
if(args.length != 2) {
System.out.println("Usage: CopyFile from to");
return; }
try { // Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} Indian Institute of Information TechnologyKottayam 10
catch(IOException e) {
System.out.println("I/O Error: " + e);
} finally{
try {
if(fin != null) fin.close();
} catch(IOException e2) {
System.out.println("Error Closing Input File");
}
try {
if(fout != null) fout.close();
} catch(IOException e2) {
System.out.println("Error Closing Output File");
}
}
}
}
1
1
Kristu Jayanti College

More Related Content

Similar to Various types of File Operations in Java (20)

File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfaces
 
Data file handling
Data file handlingData file handling
Data file handling
 
File operations
File operationsFile operations
File operations
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java IO
Java IOJava IO
Java IO
 
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
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 
Files and streams In Java
Files and streams In JavaFiles and streams In Java
Files and streams In Java
 
Data file handling
Data file handlingData file handling
Data file handling
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
File management
File managementFile management
File management
 

More from RanjithaM32

Unit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxUnit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxRanjithaM32
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxRanjithaM32
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxRanjithaM32
 
Html introduction
Html introductionHtml introduction
Html introductionRanjithaM32
 
Types of learning
Types of learningTypes of learning
Types of learningRanjithaM32
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base systemRanjithaM32
 

More from RanjithaM32 (13)

svm.ppt
svm.pptsvm.ppt
svm.ppt
 
Unit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxUnit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptx
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptx
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptx
 
Lisp.pptx
Lisp.pptxLisp.pptx
Lisp.pptx
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Html introduction
Html introductionHtml introduction
Html introduction
 
Threads
ThreadsThreads
Threads
 
Types of learning
Types of learningTypes of learning
Types of learning
 
Ml introduction
Ml introductionMl introduction
Ml introduction
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base system
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Various types of File Operations in Java

  • 1. Dr.Ranjitha M Department of Computer Science[PG] Kristu Jayanti College, Bengaluru 1 Kristu Jayanti College
  • 2. Files and operations in Java 2 Kristu Jayanti College
  • 3. java.io package • java.io package contains almost every class you need to perform input and output (I/O) in Java. • Java programs perform I/O through streams. • A stream is an abstraction that either produces or consumes information. • A stream is linked to a physical device by the Java I/O system. • All streams behave in the same manner, even if the actual physical devices to which they are linked differ. 3 Kristu Jayanti College
  • 4. java.io package • Same I/O classes and methods can be applied to different types of devices. • input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. • Streams are a clean way to deal with input/ output without having every part of your code understand the difference between a keyboard and a network. 4 Kristu Jayanti College
  • 5. File operations • Two of the most often-used stream classes are FileInputStream and FileOutputStream • Toopen a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. FileInputStream(String fileName) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException • FileNotFoundException is a subclass of IOException. • When an output file is opened, any preexisting file by the same name is destroyed. 5 Kristu Jayanti College
  • 6. File operations • When you are done with a file, you must close it. • This is done by calling the close( ) method, which is implemented by both FileInputStream and FileOutputStream. void close( ) throws IOException • Closing a file releases the system resources allocated to the file, allowing them to be used by another file. • Failure to close a file can result in “memory leaks” because of unused resources remaining allocated. 6 Kristu Jayanti College
  • 7. File operations • Toread from a file, you can use a version of read( ) that is defined within FileInputStream. int read( ) throws IOException • Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. • read( ) returns –1 when the end of the file is encountered. • It can throw an IOException. 7 Kristu Jayanti College
  • 8. File operation in Java import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; if(args.length != 1) {// First, confirm that a filename has been specified. System.out.println("Usage: ShowFile filename"); return; } try { // Attempt to open the file. fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("Cannot Open File"); return; } // At this point, the file is open and can be read. try { // The following reads characters until EOF is encountered. do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(IOException e) { System.out.println("Error Reading File"); } try { // Close the file fin.close(); } catch(IOException e) { System.out.println("Error Closing File"); } } } 8 Kristu Jayanti College
  • 9. File operation in Java import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin = null; if(args.length != 1) {// First, confirm that a filename has been specified. System.out.println("Usage: ShowFile filename"); return; } try { // Attempt to open the file. fin = new FileInputStream(args[0]); do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(FileNotFoundException e) { System.out.println("Cannot Open File"); return; } catch(IOException e) { System.out.println("Error Reading File"); } finally { // Close file in allcases. try { if(fin != null) fin.close(); } catch(IOException e) { System.out.println("Error Closing File"); } }// End finally }//End main }//End class 9 Kristu Jayanti College
  • 10. File operations • Towrite to a file, you can use the write( ) method defined by FileOutputStream. void write(int byteval) throws IOException • This method writes the byte specified by byteval to the file. • Although byteval is declared as an integer, only the low-order eight bits are written to the file. • If an error occurs during writing, an IOException is thrown. 1 0 Kristu Jayanti College
  • 11. File operation in Java import java.io.*; class CopyFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin = null; FileOutputStream fout = null; // First, confirm that both files have been specified. if(args.length != 2) { System.out.println("Usage: CopyFile from to"); return; } try { // Attempt to open the files. fin = new FileInputStream(args[0]); fout = new FileOutputStream(args[1]); do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } Indian Institute of Information TechnologyKottayam 10 catch(IOException e) { System.out.println("I/O Error: " + e); } finally{ try { if(fin != null) fin.close(); } catch(IOException e2) { System.out.println("Error Closing Input File"); } try { if(fout != null) fout.close(); } catch(IOException e2) { System.out.println("Error Closing Output File"); } } } } 1 1 Kristu Jayanti College