SlideShare une entreprise Scribd logo
1  sur  18
Introduction to File Handling
Whenever we run Java program, it is executed in RAM and hence once
we close Java and reopen it, the data i.e. the output is not saved. Till
now we have used variables and arrays to store the data but:
a. The data is lost when a variable goes out of scope or when the
program is terminated.
b. It is difficult to handle large amount of data using variables and
arrays.
Hence, to overcome this issue we use secondary storage devices
like floppy disk, hard disk to store data permanently. In secondary
storage devices the data is stored in the format of files. Storing and
managing data using files is known as file processing or file
handling.
File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.
Concept of Stream:
In File Handling, input refers to the flow of data into a program and
output means the flow of data out of a program. Input to a program
may come from Keyboard, mouse, memory, disk or from an another
program. Similarly, output from a program may go the screen,
printer, memory, disk or to an another program.
Introduction to File Handling:
Stream in Java is a path along which data flows. It has a source and a
destination. A stream presents a uniform, easy-to-use, object-
oriented interface between the program and the input/output
devices.
There are two major concepts:
a. Read from file -> Input Stream
b. Write to file -> Output Stream
1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input
stream is used to read data from numerous input devices like the keyboard,
network, etc. InputStream is an abstract class, and because of this, it is not
useful by itself. However, its subclasses are used to read data.
There are several subclasses of the InputStream class, which are as follows:
1.AudioInputStream
2.ByteArrayInputStream
3.FileInputStream
4.FilterInputStream
5.StringBufferInputStream
6.ObjectInputStream
Creating an InputStream
InputStream obj = new FileInputStream();
2. Output Stream:
The output stream is used to write data to numerous output devices
like the monitor, file, etc. OutputStream is an abstract superclass
that represents an output stream. OutputStream is an abstract
class and because of this, it is not useful by itself. However, its
subclasses are used to write data.
There are several subclasses of the OutputStream class which are
as follows:
1.ByteArrayOutputStream
2.FileOutputStream
3.StringBufferOutputStream
4.ObjectOutputStream
5.DataOutputStream
6.PrintStream
Creating an OutputStream
OutputStream obj = new FileOutputStream();
Stream Classes
The java.io package contains a large number of stream classes
that provide capabilities for processing all types of data. The following
classification shows the concept of stream classes in Java.
Create a File:
To create a file in Java, we use the createNewFile() method.
This method returns a boolean value: "true" if the file was
successfully created, and "false" if the file already exists. Note that
the method is enclosed in a try...catch block. This is necessary
because it throws an IOExcetion if an error occurs (if the file cannot
be created for some reason).
When we use createNewFile() method and provide only the
filename, the file is created in the same directory where we have
saved the program.
To create a file in a specific directory (requires permission), specify
the path of the file and use double backslashes to escape the ""
character (for Windows). On Mac and Linux you can just write the
path, like: /Users/name/filename.txt
import java.io.File;
import java.io.IOException;
public class filehandcreate
{
public static void main(String[] args)
{
try
{
File f1=new File("file1.txt");
if(f1.createNewFile())
{
System.out.println("file created "+ f1.getName());
}
else
{
System.out.println("file already exists.");
}
}
catch(IOException e)
{
System.out.println(e);
e.printStackTrace(); // it returns where the exception is occurred
}
}
}
Creating file at desired location
import java.io.File;
import java.io.IOException;
public class CreateFileex1 {
public static void main(String[] args) {
try {
File f1=new File("F:JAVAjava pptsahil.txt");
if(f1.createNewFile())
{
System.out.println("file created sucessfully");
}
else
{
System.out.println("file already exits ");
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Write To a File:
Let's move further and in the following example, we
use the FileWriter class together with its write() method to
write some text to the file we created in the example
above. Note that when you are done writing to the file, you
should close it with the close() method.
Read a File
you learned how to create and write to a file.
In the following example, we use the Scanner class to
read the contents of the text file we created in the
previous chapter:
import java.io.IOException;
public class fileex1{
public static void main(String[] args) {
File myFile = new File(“exfile1.txt");
try {
FileWriter fW = new FileWriter(“exfile1.txt");
fW.write(“hello everyone !how are you");
fW.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using Reader class
import java.io.*;
public class readfileex1 {
public static void main(String[] args) {
char a[]=new char[10000];
try {
FileReader fr=new FileReader("C:UsersSUREBITeclipse-workspaceAshwini.txt");
fr.read(a);
System.out.println(a);
fr.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class fileex2 {
public static void main(String[] args) {
File myFile = new File("exfile1.txt");
try {
Scanner sc = new Scanner(myFile);
while(sc.hasNextLine()){
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
package FileHandling;
import java.util.*;
import java.io.File;
import java.io.IOException;
public class readfileEx2 {
public static void main(String[] args) {
File f=new File("C:UsersSUREBITeclipse-workspaceAshwini.txt");
try {
Scanner sc=new Scanner(f);
while(sc.hasNextLine()) {
String line =sc.nextLine();
System.out.println(line );
}
}
catch(Exception d)
{
System.out.println(d);
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class fileex3{
public static void main(String[] args) {
File myFile = new File(“exfile1.txt");
if(myFile.delete()){
System.out.println("I have deleted: " + myFile.getName());
}
else{
System.out.println("Some problem occurred while deleting the file");
}
}
}
Methods
1) getName(): it returns the name of the file
ex: String a =f1. getName():
2) getAbsolutePath() : it returns the complete path or location of file
ex. System.out.println(f1. getAbsolutePath());
3) exists(): it returns the boolean value , true if the file is already
created.
boolean a =f1. exists();
4) canWrite(): it returns the boolean value , true if we can write into
file
boolean a =f1. canWrite();
5) canRead(): it returns the boolean value , true if we can read the
file
boolean a =f1. canWrite();
6) length():it returns the size of the file in byte
Int a=f1.length();
import java.io.File; // Import the File class
public class getinfo
{
public static void main(String[] args)
{
File myObj = new File("file1.txt");
if (myObj.exists())
{
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
}
else
{
System.out.println("The file does not exist.");
}
}
}
File Handling.pptx

Contenu connexe

Similaire à File Handling.pptx

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
 
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OWebStackAcademy
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
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
 
Various types of File Operations in Java
Various types of  File Operations in JavaVarious types of  File Operations in Java
Various types of File Operations in JavaRanjithaM32
 
File management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File ConceptsANUSUYA S
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docxtheodorelove43763
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfPRATIKSINHA7304
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfVithalReddy3
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingGurpreet singh
 

Similaire à File Handling.pptx (20)

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 Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/OCore Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
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
 
Various types of File Operations in Java
Various types of  File Operations in JavaVarious types of  File Operations in Java
Various types of File Operations in Java
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
File management in C++
File management in C++File management in C++
File management in C++
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
 
Jstreams
JstreamsJstreams
Jstreams
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 
Basic input-output-v.1.1
Basic input-output-v.1.1Basic input-output-v.1.1
Basic input-output-v.1.1
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Java I/O
Java I/OJava I/O
Java I/O
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdf
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 

Dernier

SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Dernier (20)

SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

File Handling.pptx

  • 1. Introduction to File Handling Whenever we run Java program, it is executed in RAM and hence once we close Java and reopen it, the data i.e. the output is not saved. Till now we have used variables and arrays to store the data but: a. The data is lost when a variable goes out of scope or when the program is terminated. b. It is difficult to handle large amount of data using variables and arrays. Hence, to overcome this issue we use secondary storage devices like floppy disk, hard disk to store data permanently. In secondary storage devices the data is stored in the format of files. Storing and managing data using files is known as file processing or file handling. File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it. In simple words, file handling means reading and writing data to a file.
  • 2. Concept of Stream: In File Handling, input refers to the flow of data into a program and output means the flow of data out of a program. Input to a program may come from Keyboard, mouse, memory, disk or from an another program. Similarly, output from a program may go the screen, printer, memory, disk or to an another program.
  • 3. Introduction to File Handling: Stream in Java is a path along which data flows. It has a source and a destination. A stream presents a uniform, easy-to-use, object- oriented interface between the program and the input/output devices. There are two major concepts: a. Read from file -> Input Stream b. Write to file -> Output Stream
  • 4. 1. Input Stream: The Java InputStream class is the superclass of all input streams. The input stream is used to read data from numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful by itself. However, its subclasses are used to read data. There are several subclasses of the InputStream class, which are as follows: 1.AudioInputStream 2.ByteArrayInputStream 3.FileInputStream 4.FilterInputStream 5.StringBufferInputStream 6.ObjectInputStream Creating an InputStream InputStream obj = new FileInputStream();
  • 5. 2. Output Stream: The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not useful by itself. However, its subclasses are used to write data. There are several subclasses of the OutputStream class which are as follows: 1.ByteArrayOutputStream 2.FileOutputStream 3.StringBufferOutputStream 4.ObjectOutputStream 5.DataOutputStream 6.PrintStream Creating an OutputStream OutputStream obj = new FileOutputStream();
  • 6. Stream Classes The java.io package contains a large number of stream classes that provide capabilities for processing all types of data. The following classification shows the concept of stream classes in Java.
  • 7. Create a File: To create a file in Java, we use the createNewFile() method. This method returns a boolean value: "true" if the file was successfully created, and "false" if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOExcetion if an error occurs (if the file cannot be created for some reason). When we use createNewFile() method and provide only the filename, the file is created in the same directory where we have saved the program. To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt
  • 8. import java.io.File; import java.io.IOException; public class filehandcreate { public static void main(String[] args) { try { File f1=new File("file1.txt"); if(f1.createNewFile()) { System.out.println("file created "+ f1.getName()); } else { System.out.println("file already exists."); } } catch(IOException e) { System.out.println(e); e.printStackTrace(); // it returns where the exception is occurred } } }
  • 9. Creating file at desired location import java.io.File; import java.io.IOException; public class CreateFileex1 { public static void main(String[] args) { try { File f1=new File("F:JAVAjava pptsahil.txt"); if(f1.createNewFile()) { System.out.println("file created sucessfully"); } else { System.out.println("file already exits "); } } catch(IOException e) { System.out.println(e); } } }
  • 10. Write To a File: Let's move further and in the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method. Read a File you learned how to create and write to a file. In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter:
  • 11. import java.io.IOException; public class fileex1{ public static void main(String[] args) { File myFile = new File(“exfile1.txt"); try { FileWriter fW = new FileWriter(“exfile1.txt"); fW.write(“hello everyone !how are you"); fW.close(); } catch (IOException e) { e.printStackTrace(); } } }
  • 12. Using Reader class import java.io.*; public class readfileex1 { public static void main(String[] args) { char a[]=new char[10000]; try { FileReader fr=new FileReader("C:UsersSUREBITeclipse-workspaceAshwini.txt"); fr.read(a); System.out.println(a); fr.close(); } catch(IOException e) { System.out.println(e); } } }
  • 13. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class fileex2 { public static void main(String[] args) { File myFile = new File("exfile1.txt"); try { Scanner sc = new Scanner(myFile); while(sc.hasNextLine()){ String line = sc.nextLine(); System.out.println(line); } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
  • 14. package FileHandling; import java.util.*; import java.io.File; import java.io.IOException; public class readfileEx2 { public static void main(String[] args) { File f=new File("C:UsersSUREBITeclipse-workspaceAshwini.txt"); try { Scanner sc=new Scanner(f); while(sc.hasNextLine()) { String line =sc.nextLine(); System.out.println(line ); } } catch(Exception d) { System.out.println(d); } } }
  • 15. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class fileex3{ public static void main(String[] args) { File myFile = new File(“exfile1.txt"); if(myFile.delete()){ System.out.println("I have deleted: " + myFile.getName()); } else{ System.out.println("Some problem occurred while deleting the file"); } } }
  • 16. Methods 1) getName(): it returns the name of the file ex: String a =f1. getName(): 2) getAbsolutePath() : it returns the complete path or location of file ex. System.out.println(f1. getAbsolutePath()); 3) exists(): it returns the boolean value , true if the file is already created. boolean a =f1. exists(); 4) canWrite(): it returns the boolean value , true if we can write into file boolean a =f1. canWrite(); 5) canRead(): it returns the boolean value , true if we can read the file boolean a =f1. canWrite(); 6) length():it returns the size of the file in byte Int a=f1.length();
  • 17. import java.io.File; // Import the File class public class getinfo { public static void main(String[] args) { File myObj = new File("file1.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); } else { System.out.println("The file does not exist."); } } }