SlideShare a Scribd company logo
1 of 15
UNIT-6
FILE HANDLING
• Describing the basics of input and output in Java,
• read and write data from the console,
• File streams, using streams to read and write files, using the path
interface to operate on file, using the path interface to operate on
directory paths,
• using the files class to check, delete, copy, or move a file, or move a
directory
File handling in Java
• File handling in Java means that how to read from and write to file in Java.
• Java provides the basic I/O package for reading and writing streams.
• java.io package allows to do all Input and Output tasks in Java .
What is Stream
• an object that either delivers data to its destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
• A stream in java is a path along which data flows
It can be of two types :
Byte Stream and Character Stream.
When an I/O stream manages 8-bit bytes of binary data, it is called a byte stream.
And, when the I/O stream manages 16-bit Unicode characters, it is called a
character stream.
• Stream – A sequence of data.
Input Stream: reads data from source.
Output Stream: writes data to destination.
• Byte oriented reads byte by byte. A byte stream is suitable for
processing raw data like binary files.
• Character stream is useful when we want to process text files. These
text files can be processed character by character.
Byte Stream classes:
Byte Stream
Character Stream classes:
• Byte Stream Classes Example: using InputStream and OutputStream
• ByteStreamEx.java
• Character Stream Classes Example: using FileWriter and FileReader
• CharacterStreamEx.java
read and write data from the console
• In Java, there are three different ways for reading input from the user
in the command line environment(console).
• 1.Using Buffered Reader Class
• 2. Using Scanner Class
• 3. Using Console Class
using the path interface to operate on file
• The Path interface is located in the java.nio.file package, so the fully
qualified name of the Java Path interface is java.nio.file.Path.
• A Java Path instance represents a path in the file system. A path can
point to either a file or a directory.
• A path can be absolute or relative.
• An absolute path contains the full path from the root of the file
system down to the file or directory it points to.
• A relative path contains the path to the file or directory relative to
some other path.
Example:
import java.nio.file.*;
public class PathExample {
public static void main(String[] args)
{
Path path = Paths.get("E:LPUmyfile.txt");
System.out.println(path.getFileName().toString());
}
}
Copy a file
import java.io.*;
class file_copy {
public static void main(String[] args) {
try {
File inputFile = new File("file1.txt");
File outputFile = new File("file2.txt");
FileInputStream fis = new
FileInputStream(inputFile);
FileOutputStream fos = new
FileOutputStream(outputFile);
int c;
while ((c = fis.read()) != -1) {
fos.write(c);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}
}
}
Moving a file
import java.io.File;
public class file_move
{
public static void main(String[] args)
{
try{
File mv =new File("newfile.txt");
if(mv.renameTo(new File("F:" + mv.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Deleting a file
import java.io.*;
public class file_del
{
public static void main(String[] args)
{
File file = new File("newfile.txt");
if(file.delete())
{
System.out.println("File deleted
successfully");
}
else
{
System.out.println("Failed to delete the
file");
}
}
}
Append to File using PrintWriter: Use PrintWriter to write
formatted text to a file.
public static void usingPrintWriter() throws IOException
{
String textToAppend = “Java programming";
FileWriter fileWriter = new FileWriter("c:/samplefile.txt", true);
//Set true for append mode
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println(textToAppend); //New line
printWriter.close();
}
Practice Programs
• WAP to count vowels in a file
• WAP to count the number of characters from a file
• WAP to check whether the file is present in the specified location or
not

More Related Content

What's hot

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 
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 javaJayasankarPR2
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51myrajendra
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Javaiostream
JavaiostreamJavaiostream
JavaiostreamTien Nguyen
 
Data file handling
Data file handlingData file handling
Data file handlingSaurabh Patel
 
File Handling
File HandlingFile Handling
File HandlingWaqar Ali
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))Papu Kumar
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2Tanmay Baranwal
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52myrajendra
 

What's hot (20)

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
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
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
Data file handling
Data file handlingData file handling
Data file handling
 
Filehandling
FilehandlingFilehandling
Filehandling
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
 

Similar to JAVA

CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streamsHamid Ghorbani
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
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 referenceanuvayalil5525
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization Hitesh-Java
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, SerializationPawanMM
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2Gera Paulos
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 
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
 
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?kanchanmahajan23
 
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?kanchanmahajan23
 

Similar to JAVA (20)

CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java I/O
Java I/OJava I/O
Java I/O
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
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
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
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
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Advanced programming ch2
Advanced programming ch2Advanced programming ch2
Advanced programming ch2
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
File Handling
File HandlingFile Handling
File Handling
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
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)
 
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?
 

More from LOVELY PROFESSIONAL UNIVERSITY

More from LOVELY PROFESSIONAL UNIVERSITY (19)

Enumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFTEnumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFT
 
Dictionaries IN SWIFT
Dictionaries IN SWIFTDictionaries IN SWIFT
Dictionaries IN SWIFT
 
Control structures IN SWIFT
Control structures IN SWIFTControl structures IN SWIFT
Control structures IN SWIFT
 
Arrays and its properties IN SWIFT
Arrays and its properties IN SWIFTArrays and its properties IN SWIFT
Arrays and its properties IN SWIFT
 
Array and its functionsI SWIFT
Array and its functionsI SWIFTArray and its functionsI SWIFT
Array and its functionsI SWIFT
 
practice problems on array IN SWIFT
practice problems on array IN SWIFTpractice problems on array IN SWIFT
practice problems on array IN SWIFT
 
practice problems on array IN SWIFT
practice problems on array  IN SWIFTpractice problems on array  IN SWIFT
practice problems on array IN SWIFT
 
practice problems on array IN SWIFT
practice problems on array IN SWIFTpractice problems on array IN SWIFT
practice problems on array IN SWIFT
 
practice problems on functions IN SWIFT
practice problems on functions IN SWIFTpractice problems on functions IN SWIFT
practice problems on functions IN SWIFT
 
10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
 
Variables and data types IN SWIFT
 Variables and data types IN SWIFT Variables and data types IN SWIFT
Variables and data types IN SWIFT
 
Soft skills. pptx
Soft skills. pptxSoft skills. pptx
Soft skills. pptx
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 3
Unit 3Unit 3
Unit 3
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Unit 1
Unit 1Unit 1
Unit 1
 
COMPLETE CORE JAVA
COMPLETE CORE JAVACOMPLETE CORE JAVA
COMPLETE CORE JAVA
 
Data wrangling IN R LANGUAGE
Data wrangling IN R LANGUAGEData wrangling IN R LANGUAGE
Data wrangling IN R LANGUAGE
 

Recently uploaded

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

JAVA

  • 2. FILE HANDLING • Describing the basics of input and output in Java, • read and write data from the console, • File streams, using streams to read and write files, using the path interface to operate on file, using the path interface to operate on directory paths, • using the files class to check, delete, copy, or move a file, or move a directory
  • 3. File handling in Java • File handling in Java means that how to read from and write to file in Java. • Java provides the basic I/O package for reading and writing streams. • java.io package allows to do all Input and Output tasks in Java . What is Stream • an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) • A stream in java is a path along which data flows It can be of two types : Byte Stream and Character Stream. When an I/O stream manages 8-bit bytes of binary data, it is called a byte stream. And, when the I/O stream manages 16-bit Unicode characters, it is called a character stream.
  • 4. • Stream – A sequence of data. Input Stream: reads data from source. Output Stream: writes data to destination. • Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files. • Character stream is useful when we want to process text files. These text files can be processed character by character.
  • 7. • Byte Stream Classes Example: using InputStream and OutputStream • ByteStreamEx.java • Character Stream Classes Example: using FileWriter and FileReader • CharacterStreamEx.java
  • 8. read and write data from the console • In Java, there are three different ways for reading input from the user in the command line environment(console). • 1.Using Buffered Reader Class • 2. Using Scanner Class • 3. Using Console Class
  • 9. using the path interface to operate on file • The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. • A Java Path instance represents a path in the file system. A path can point to either a file or a directory. • A path can be absolute or relative. • An absolute path contains the full path from the root of the file system down to the file or directory it points to. • A relative path contains the path to the file or directory relative to some other path.
  • 10. Example: import java.nio.file.*; public class PathExample { public static void main(String[] args) { Path path = Paths.get("E:LPUmyfile.txt"); System.out.println(path.getFileName().toString()); } }
  • 11. Copy a file import java.io.*; class file_copy { public static void main(String[] args) { try { File inputFile = new File("file1.txt"); File outputFile = new File("file2.txt"); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); int c; while ((c = fis.read()) != -1) { fos.write(c); } fis.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println("FileStreamsTest: " + e); } catch (IOException e) { System.err.println("FileStreamsTest: " + e); } } }
  • 12. Moving a file import java.io.File; public class file_move { public static void main(String[] args) { try{ File mv =new File("newfile.txt"); if(mv.renameTo(new File("F:" + mv.getName()))){ System.out.println("File is moved successful!"); }else{ System.out.println("File is failed to move!"); } }catch(Exception e){ e.printStackTrace(); } } }
  • 13. Deleting a file import java.io.*; public class file_del { public static void main(String[] args) { File file = new File("newfile.txt"); if(file.delete()) { System.out.println("File deleted successfully"); } else { System.out.println("Failed to delete the file"); } } }
  • 14. Append to File using PrintWriter: Use PrintWriter to write formatted text to a file. public static void usingPrintWriter() throws IOException { String textToAppend = “Java programming"; FileWriter fileWriter = new FileWriter("c:/samplefile.txt", true); //Set true for append mode PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.println(textToAppend); //New line printWriter.close(); }
  • 15. Practice Programs • WAP to count vowels in a file • WAP to count the number of characters from a file • WAP to check whether the file is present in the specified location or not