SlideShare a Scribd company logo
File Handling in Java
In general terms, a file is a collection of information. In Java, a file is an abstract type
that stores related information together. This article will let you know about the file
and its various useful operations. But before getting to know about it, you must have
a clear idea about Stream and File Methods in Java.
Standard streams in Java:
A stream is a series of data. It helps us perform I/O operations with a file. The
operating system will define three standard streams. The need for standard Input
and Output us necessary. This is where a user can take input from a keyboard and
result in producing an output on the monitor. Though the input and output devices
may vary, the process is the same. In C and C++, there are three standard devices
STDIN, STDOUT and STDERR.
It ensures that these standard streams are accessible via the members of the
system class in Java:
1. Standard Input: It provides input data to the program. This task is mostly
accomplished by a keyboard that is used as a standard input stream and is denoted
as System.in.
2. Standard Output: It provides the result of the data that that program produces. this
output is usually displayed on the computer screen which is the standard output
stream and is denoted as System.out.
3. Standard Error: It displays the error data that the program produces. This is
usually displayed on the computer screen that is used as the standard error stream
and is represented as System.err.
Input Stream in Java:
The superclass of all input streams is the Java InputStream class. We use input
devices like the keyboard, network, etc., to read the input. This InputStream is also
an abstract class.
The various subclasses of the InputStream class are:
■ AudioInputStream
■ ByteArrayInputStream
■ FileInputStream
■ FilterInputStream
■ StringBufferUnputStream
■ ObjectInputStream
Creating an Input Stream in java:
InputStream obj = new FileInputStream();
S.n
o
Method Description
1 read() We can use this to read a byte of date from the input stream.
2
read(byte[]
array)()
It reads a byte from the stream and lets us store the byte in the
mentioned array.
3 mark() It marks the position in the input stream till the data is read.
4 available() It returns the number of bytes from the input stream.
5 markSupported() It checks if the mark() method and result() method in the system.
6 reset() It returns the control to the point where the mark was set.
7 skips()
It skips and removes the mentioned number of bytes from the input
stream.
8 close() It closes the input stream.
9 finalize()
It cleans the connection to the file. It also ensures that the close
method
Sample program to create InputStreamReader to read the standard input stream
until the code word for quit, ‘q’ is entered by the user:
import java.io.*;
public class FirstCodeReadConsole {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter the character 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Output:
1
2
r
q
q
Output stream in Java:
The output stream gives the ability to write data into various output devices. These
devices include the monitor, printer and even file. OutputStream is an abstract
superclass to represent the output stream.
The various subclasses under the output stream class are:
■ ByteArrayOutputStream
■ FileOutputStream
■ StringBufferOutputStream
■ DataOutputStream
■ PrintStream
Creating an OutputStream:
OutputStream obj = new FileOutputStream();
S.N
o
Method Description
1 write() It writes the specified byte to the output stream.
2
write(byte[]
array)
It writes the bytes which are given in a specific array to the output
stream
3 close() It closes the output stream
4 flush()
It forces to write all the data present in an output stream to its
destination
5 finalize()
It cleans the connection to the file. It ensures that the close method if the
file outstream is invoked in the absence of other references to the
stream.
Output Streams Operations in Java:
There are three methods to write the data into a stream. These methods are
available in the Independent output stream. These mirror the read() methods
present in the Input Stream Class, which is also an abstract class.
Output Streams Operations Description
FileOutputStream To write a file
ObjecyInputStream To write objects to a stream
ByteArrayOutputStream To write an array of bytes
PipeOutputStream To write to a piped stream
FilterOutputStream To filter the output from an end stream
Based on the data type, the stream is divided into two categories:
1. Byte Stream
2. Character Stream
Classification of I/O streams in java:
1. Byte Stream:
Byte Stream takes place with byte data. In this type of file handling method, the byte
stream process allows execution with byte data.
2. Character Stream:
It takes place with character data. In this type of file handling method, the character
stream process allows execution with character data.
Java File Class Methods:
S.N
o
Method
Return
Type
Description
1 canRead() Boolean
Using this method, we can check if the file can be
read or not.
2 createNewFile() Boolean We can use this method to create a new file.
3 canWrite() Boolean It lets us check if we can write in the file or not.
4 exists() Boolean
It is used to check if the mentioned file is available
or not.
5 delete() Boolean Using this method, we can delete a file.
6 getName() String
We can use this method to find the name of the
file.
7
getAbsolutePath
()
String
This method helps us in knowing the absolute
pathname of the file.
8 length() Long It lets us attain the size of the files in bytes
9 list() String[]
Using this method, we can get the array of files in
the directory
10 mkdir() Boolean We can use this method to create a new directory
What is File handling in Java?
File handling is the process of reading and writing data into a file. The File class in
Java is present in the java.io package. We can simply use the file class by creating
an object for the class and specifying the name of the file or directory.
Why is File handling required?
To begin with, let us first understand the importance of this concept.
File handling is an integral part of every programming language. Storing the output
of a program in a file format makes it easily retrievable. Therefore, file handling is an
essential part of programming.
Java File Operations:
The various operations that we can perform in a file in java are listed below:
■ Creating a file
■ Getting file information
■ Writing into a file
■ Reading from a file
■ Deleting a file
1. File creation in Java:
The File Creation operation lets us create a new file. The method that performs this
action is the createNewFile() method. It returns true after successfully creating a
new file. If the field name already exists, this method returns false.
Sample program to create a file in Java:
import java.io.File;
import java.IOException;
class FirstCode{
public static void main(String args[]){
try{
File f() = new File(“D:CreatingFileExample.txt”);
if(f().createNewFile()){
System.out.println(“The file” + f().getName() + “is created succefully.”);
}else{
System.out.println(“The file name already exists in the directory”);
}
}catch(IOException exception){
System.out.println(“Error!!!”);
exception.printStackTrace();
}
}
}
2. Read from a file / Get File Information:
We perform this operation to retrieve the data from the file. Some of the methods
that let us achieve this are name, absolute path, is readable, is writeable and length.
Sample program to read information from a file:
import java.io.File;
class FirstCode{
public static void main(String args[]){
File f() = new File(“D:ReadingFileExample.txt”);
if(f().exists()){
System.out.println(“The file name is: ”+f()getName()); // to get file name
System.out.println(“The absolute path is: ”+f().getAbsolutepath()); // to get file
path
// to check it the file is writeable or not
System.out.println(“Is the file writeable?” +f().canWrite());
// to check if the file is readable or not
System.out.println(“Is the file readable?” +f().canRead());
// to get the length of the file
System.out.println(“The size of the file in bytes is: ”+f().length());
}else{
System.out.println(“The file does not exist”);
}
}
}
3. Write into a file:
To write into a file, we use the FileWriter class and the write() method. The stream
should be closed using the close() method to retrieve the resources.
Sample program to write into a file:
import java.io.FileWriter;
import java.io.IOException;
class FirstCode{
public static void main(String args[]){
try{
FileWriter fwrite = new FileWriter(“D:FileWritingExample.txt”);
fwrite.write(“Learn Java with FirstCode”);
fwrite.close();
System.out.println(“Content is successfully written in the file”);
}
catch(IOException e){
System.out.println(“Error!!!”);
e.printStackTerrace();
}
}
}
Java FileWriter:
This class in Java helps the programmers to create new file writing characters. It
inherits from the OutputStream class.
The constructors present in this class generally assume that the byte-buffer size and
default character encoding are acceptable. To declare these constructors, we must
construct OutputStreamWriter on a FileOutputStream.
The Java FileWriter is very much useful for writing streams of
characters.constructors
4. Read from a file in java:
To read the content present in the file, we need to use the Scanner class. The
stream is closed using the close() method. We can create an object for the Scanner
class to implement the hasNextLine() and nextLine() methods. These methods
retrieve the information from the file.
Java FileReader:
The FileReader in Java plays a vital role in reading the data that is present in the
form of characters. This is done in the form of a ‘text’ file. The FileReader inherits
from the InputStreamReader class.
The constructors in this class assume the default character encoding and the default
byte are appropriate. As the Java FileReader is used only for particularly reading
streams of character, you can use the FileInputStream to read streams of raw bytes.
Methods:
Methods Description
public int read() throws
IOException
This method read a single character and blocks one until
another one is available. That is, an input/ output error
occurs.
public int read(char[] cbuff[])
throws IOException
It reads characters into an array and blocks until a
character is available.
public abstract int read(char[]
buff, int off, int len) which throws
an IOException
It read characters into a portion of an array. It blocks until
the input is available or an error occurs in the input and
output, or the end of the stream is reached.
Parameters:
■ cbuff – Destination buffer.
■ off – It sets the offset at which to start storing characters.
■ len – it uses to see the maximum number of characters to read.
■ public long skip(long n) throws IOException: It skips the characters and
blocks until some characters are available, an I/O error occurs or the
stream end is reached.
Sample program to read from a file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class FirstCode{
public static void main(String args[]){
try{
File f = new File(“D:ReadFromFile.txt”);
Scanner s =new Scanner(f);
while(s.hasNextLine()){
String fileData = s.nextLine();
System.out.println(fileData);
}
s.close();
}catch(FileNotFoundException exception){
System.out.println(“Error!!!”);
exception.printStackTrace();
}
}
}
Deleting a file:
Knowing to delete a file is as important as creating one. The delete() method
performs this task. We need not close the stream with the close() method or use the
FileWriter and Scanner class here.
Sample program to delete a file:
import java.io.File;
class FirstCode{
public static void main(String args[]){
File f() = new File(“D:DeletingFile.txt”);
if(f().delete()){
System.out.println(f().getname()+ “The file is deleted”);
}else{
System.out.println(“Error!!!”);
}
}
}
Java Directories:
Methods to create and modify files and directories in
java:
Methods Description
renameTo(File
path)
The file that the current object represents will be renamed to the path that
the file object passes as an argument to the method.
setreadonly()
It sets the files that represent the current object as read-only and returns
true when the task is succeeded.
mkdir() It creates a directory with the path specified by the current file object.
mkdirs()
Creates the directory represented by the current file object, including
parent directories that are required.
createanewfile()
It creates a new empty file with a pathname defined by the current file
object as long as the file exists.
delete()
This deletes the file in a directory represented by the current file object and
returns true if the delete is successful.
createDirectory(Path, FileAttribute</>)
Creating Directories in java:
Java provides a couple of beneficial File utility methods that are used to create
directories.
■ The mkdir() method creates a directory. It returns true for success and
false for failure. The failure denotes that the path that is mentioned in the
File object exists already. It also denotes that the directory cannot be
created if the path does not exist.
■ The mkdirs() methods create both a directory and also parents of the
directory.
Sample program to create a directory:
import java.io.File;
public class CreateDirFirstCode{
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
d.mkdirs();
}
}
Listing directories in Java
The File object provides the list() method to list down all the files and directories that
are present.
Sample program to list the directories:
import java.io.File;
public class ReadDirFirstCode {
public static void main(String[] args) {
File file = null;
String[] paths;
try {
file = new File("/tmp");
paths = file.list();
for(String path:paths) {
System.out.println(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
test1.txttest2.txt
ReadDir.java
ReadDir.class
Querying Files and Directories in Java:
Method Description
exists()
It returns if the file or directory referred to by the file object exists and false
otherwise
isfile() It returns if the file object refers to an existing file and false otherwise.
canread() It returns true if it allows reading the sile that is referred by the file object.
canwrite(
)
It returns true if you are permitted to write the file referred by the file object.
Constructors:
Constructors Description
FileWriter(File file)
This constructor constructs a FileWriter object
when a file object is given.
FileWriter(File file, boolean append) It constructs an object for Filewriter.
FileWriter(FileDescriptor fd)
Constructs a FileWriter object associated using
a file descriptor.
FileWriter(String fileName)
It constructs a FileWriter object when a file
name is given.
public void write(int c) throws IOException It writes a single character.
public void write(char[] stir) throws
IOException
It writes an array of character.
public void write(String str) throws
IOException
It writes a string in Java.
FileWriter(String filename, Boolean append)
It constructs a FileWriter object when a file
name is present.
public void write(String str, int off, int len)
throws IOException
It writes a portion of a String.
Conclusion:
This article would have helped you in knowing various details about file handling in
Java. You can now create your own file and perform various file handling operations
to it. This lets you store the data and retrieve them easily.
File Handling in Java.pdf
Ad

More Related Content

What's hot (20)

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
JayasankarPR2
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Java Collections
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
Java- Nested Classes
Java- Nested ClassesJava- Nested Classes
Java- Nested Classes
Prabhdeep Singh
 
Java input
Java inputJava input
Java input
Jin Castor
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
keeeerty
 
design of accumlator
design of accumlatordesign of accumlator
design of accumlator
SangeethaSasi1
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
Files in java
Files in javaFiles in java
Files in java
Muthukumaran Subramanian
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 

Similar to File Handling in Java.pdf (20)

Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
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
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
NavneetSheoran3
 
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
WebStackAcademy
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
NguynThiThanhTho
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
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
Don Bosco BSIT
 
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
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
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
WebStackAcademy
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
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
Don Bosco BSIT
 
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
 
Ad

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
SudhanshiBakre1
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
SudhanshiBakre1
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
SudhanshiBakre1
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
SudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
SudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
SudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
SudhanshiBakre1
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
SudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
SudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
SudhanshiBakre1
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
SudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
SudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
SudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
SudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
SudhanshiBakre1
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
SudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
SudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
SudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
SudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
SudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
SudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
SudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
SudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
SudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
SudhanshiBakre1
 
Ad

Recently uploaded (20)

Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 

File Handling in Java.pdf

  • 1. File Handling in Java In general terms, a file is a collection of information. In Java, a file is an abstract type that stores related information together. This article will let you know about the file and its various useful operations. But before getting to know about it, you must have a clear idea about Stream and File Methods in Java. Standard streams in Java: A stream is a series of data. It helps us perform I/O operations with a file. The operating system will define three standard streams. The need for standard Input and Output us necessary. This is where a user can take input from a keyboard and result in producing an output on the monitor. Though the input and output devices may vary, the process is the same. In C and C++, there are three standard devices STDIN, STDOUT and STDERR. It ensures that these standard streams are accessible via the members of the system class in Java: 1. Standard Input: It provides input data to the program. This task is mostly accomplished by a keyboard that is used as a standard input stream and is denoted as System.in. 2. Standard Output: It provides the result of the data that that program produces. this output is usually displayed on the computer screen which is the standard output stream and is denoted as System.out.
  • 2. 3. Standard Error: It displays the error data that the program produces. This is usually displayed on the computer screen that is used as the standard error stream and is represented as System.err. Input Stream in Java: The superclass of all input streams is the Java InputStream class. We use input devices like the keyboard, network, etc., to read the input. This InputStream is also an abstract class. The various subclasses of the InputStream class are: ■ AudioInputStream ■ ByteArrayInputStream ■ FileInputStream ■ FilterInputStream ■ StringBufferUnputStream ■ ObjectInputStream Creating an Input Stream in java: InputStream obj = new FileInputStream(); S.n o Method Description 1 read() We can use this to read a byte of date from the input stream. 2 read(byte[] array)() It reads a byte from the stream and lets us store the byte in the mentioned array. 3 mark() It marks the position in the input stream till the data is read.
  • 3. 4 available() It returns the number of bytes from the input stream. 5 markSupported() It checks if the mark() method and result() method in the system. 6 reset() It returns the control to the point where the mark was set. 7 skips() It skips and removes the mentioned number of bytes from the input stream. 8 close() It closes the input stream. 9 finalize() It cleans the connection to the file. It also ensures that the close method Sample program to create InputStreamReader to read the standard input stream until the code word for quit, ‘q’ is entered by the user: import java.io.*; public class FirstCodeReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter the character 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c);
  • 4. } while(c != 'q'); }finally { if (cin != null) { cin.close(); } } } } Output: 1 2 r q q Output stream in Java: The output stream gives the ability to write data into various output devices. These devices include the monitor, printer and even file. OutputStream is an abstract superclass to represent the output stream. The various subclasses under the output stream class are: ■ ByteArrayOutputStream ■ FileOutputStream ■ StringBufferOutputStream ■ DataOutputStream ■ PrintStream
  • 5. Creating an OutputStream: OutputStream obj = new FileOutputStream(); S.N o Method Description 1 write() It writes the specified byte to the output stream. 2 write(byte[] array) It writes the bytes which are given in a specific array to the output stream 3 close() It closes the output stream 4 flush() It forces to write all the data present in an output stream to its destination 5 finalize() It cleans the connection to the file. It ensures that the close method if the file outstream is invoked in the absence of other references to the stream. Output Streams Operations in Java: There are three methods to write the data into a stream. These methods are available in the Independent output stream. These mirror the read() methods present in the Input Stream Class, which is also an abstract class. Output Streams Operations Description FileOutputStream To write a file
  • 6. ObjecyInputStream To write objects to a stream ByteArrayOutputStream To write an array of bytes PipeOutputStream To write to a piped stream FilterOutputStream To filter the output from an end stream Based on the data type, the stream is divided into two categories: 1. Byte Stream 2. Character Stream Classification of I/O streams in java: 1. Byte Stream: Byte Stream takes place with byte data. In this type of file handling method, the byte stream process allows execution with byte data. 2. Character Stream: It takes place with character data. In this type of file handling method, the character stream process allows execution with character data. Java File Class Methods: S.N o Method Return Type Description
  • 7. 1 canRead() Boolean Using this method, we can check if the file can be read or not. 2 createNewFile() Boolean We can use this method to create a new file. 3 canWrite() Boolean It lets us check if we can write in the file or not. 4 exists() Boolean It is used to check if the mentioned file is available or not. 5 delete() Boolean Using this method, we can delete a file. 6 getName() String We can use this method to find the name of the file. 7 getAbsolutePath () String This method helps us in knowing the absolute pathname of the file. 8 length() Long It lets us attain the size of the files in bytes 9 list() String[] Using this method, we can get the array of files in the directory 10 mkdir() Boolean We can use this method to create a new directory What is File handling in Java? File handling is the process of reading and writing data into a file. The File class in Java is present in the java.io package. We can simply use the file class by creating an object for the class and specifying the name of the file or directory.
  • 8. Why is File handling required? To begin with, let us first understand the importance of this concept. File handling is an integral part of every programming language. Storing the output of a program in a file format makes it easily retrievable. Therefore, file handling is an essential part of programming. Java File Operations: The various operations that we can perform in a file in java are listed below: ■ Creating a file ■ Getting file information ■ Writing into a file ■ Reading from a file ■ Deleting a file 1. File creation in Java: The File Creation operation lets us create a new file. The method that performs this action is the createNewFile() method. It returns true after successfully creating a new file. If the field name already exists, this method returns false. Sample program to create a file in Java: import java.io.File; import java.IOException; class FirstCode{ public static void main(String args[]){ try{
  • 9. File f() = new File(“D:CreatingFileExample.txt”); if(f().createNewFile()){ System.out.println(“The file” + f().getName() + “is created succefully.”); }else{ System.out.println(“The file name already exists in the directory”); } }catch(IOException exception){ System.out.println(“Error!!!”); exception.printStackTrace(); } } } 2. Read from a file / Get File Information: We perform this operation to retrieve the data from the file. Some of the methods that let us achieve this are name, absolute path, is readable, is writeable and length. Sample program to read information from a file: import java.io.File; class FirstCode{ public static void main(String args[]){ File f() = new File(“D:ReadingFileExample.txt”); if(f().exists()){ System.out.println(“The file name is: ”+f()getName()); // to get file name
  • 10. System.out.println(“The absolute path is: ”+f().getAbsolutepath()); // to get file path // to check it the file is writeable or not System.out.println(“Is the file writeable?” +f().canWrite()); // to check if the file is readable or not System.out.println(“Is the file readable?” +f().canRead()); // to get the length of the file System.out.println(“The size of the file in bytes is: ”+f().length()); }else{ System.out.println(“The file does not exist”); } } } 3. Write into a file: To write into a file, we use the FileWriter class and the write() method. The stream should be closed using the close() method to retrieve the resources. Sample program to write into a file: import java.io.FileWriter; import java.io.IOException; class FirstCode{ public static void main(String args[]){ try{
  • 11. FileWriter fwrite = new FileWriter(“D:FileWritingExample.txt”); fwrite.write(“Learn Java with FirstCode”); fwrite.close(); System.out.println(“Content is successfully written in the file”); } catch(IOException e){ System.out.println(“Error!!!”); e.printStackTerrace(); } } } Java FileWriter: This class in Java helps the programmers to create new file writing characters. It inherits from the OutputStream class. The constructors present in this class generally assume that the byte-buffer size and default character encoding are acceptable. To declare these constructors, we must construct OutputStreamWriter on a FileOutputStream. The Java FileWriter is very much useful for writing streams of characters.constructors 4. Read from a file in java: To read the content present in the file, we need to use the Scanner class. The stream is closed using the close() method. We can create an object for the Scanner
  • 12. class to implement the hasNextLine() and nextLine() methods. These methods retrieve the information from the file. Java FileReader: The FileReader in Java plays a vital role in reading the data that is present in the form of characters. This is done in the form of a ‘text’ file. The FileReader inherits from the InputStreamReader class. The constructors in this class assume the default character encoding and the default byte are appropriate. As the Java FileReader is used only for particularly reading streams of character, you can use the FileInputStream to read streams of raw bytes. Methods: Methods Description public int read() throws IOException This method read a single character and blocks one until another one is available. That is, an input/ output error occurs. public int read(char[] cbuff[]) throws IOException It reads characters into an array and blocks until a character is available. public abstract int read(char[] buff, int off, int len) which throws an IOException It read characters into a portion of an array. It blocks until the input is available or an error occurs in the input and output, or the end of the stream is reached. Parameters: ■ cbuff – Destination buffer. ■ off – It sets the offset at which to start storing characters. ■ len – it uses to see the maximum number of characters to read.
  • 13. ■ public long skip(long n) throws IOException: It skips the characters and blocks until some characters are available, an I/O error occurs or the stream end is reached. Sample program to read from a file: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; class FirstCode{ public static void main(String args[]){ try{ File f = new File(“D:ReadFromFile.txt”); Scanner s =new Scanner(f); while(s.hasNextLine()){ String fileData = s.nextLine(); System.out.println(fileData); } s.close(); }catch(FileNotFoundException exception){ System.out.println(“Error!!!”); exception.printStackTrace(); } } }
  • 14. Deleting a file: Knowing to delete a file is as important as creating one. The delete() method performs this task. We need not close the stream with the close() method or use the FileWriter and Scanner class here. Sample program to delete a file: import java.io.File; class FirstCode{ public static void main(String args[]){ File f() = new File(“D:DeletingFile.txt”); if(f().delete()){ System.out.println(f().getname()+ “The file is deleted”); }else{ System.out.println(“Error!!!”); } } } Java Directories: Methods to create and modify files and directories in java: Methods Description
  • 15. renameTo(File path) The file that the current object represents will be renamed to the path that the file object passes as an argument to the method. setreadonly() It sets the files that represent the current object as read-only and returns true when the task is succeeded. mkdir() It creates a directory with the path specified by the current file object. mkdirs() Creates the directory represented by the current file object, including parent directories that are required. createanewfile() It creates a new empty file with a pathname defined by the current file object as long as the file exists. delete() This deletes the file in a directory represented by the current file object and returns true if the delete is successful. createDirectory(Path, FileAttribute</>) Creating Directories in java: Java provides a couple of beneficial File utility methods that are used to create directories. ■ The mkdir() method creates a directory. It returns true for success and false for failure. The failure denotes that the path that is mentioned in the File object exists already. It also denotes that the directory cannot be created if the path does not exist. ■ The mkdirs() methods create both a directory and also parents of the directory. Sample program to create a directory: import java.io.File;
  • 16. public class CreateDirFirstCode{ public static void main(String args[]) { String dirname = "/tmp/user/java/bin"; File d = new File(dirname); d.mkdirs(); } } Listing directories in Java The File object provides the list() method to list down all the files and directories that are present. Sample program to list the directories: import java.io.File; public class ReadDirFirstCode { public static void main(String[] args) { File file = null; String[] paths; try { file = new File("/tmp"); paths = file.list(); for(String path:paths) { System.out.println(path); }
  • 17. } catch (Exception e) { e.printStackTrace(); } } } Output: test1.txttest2.txt ReadDir.java ReadDir.class Querying Files and Directories in Java: Method Description exists() It returns if the file or directory referred to by the file object exists and false otherwise isfile() It returns if the file object refers to an existing file and false otherwise. canread() It returns true if it allows reading the sile that is referred by the file object. canwrite( ) It returns true if you are permitted to write the file referred by the file object. Constructors:
  • 18. Constructors Description FileWriter(File file) This constructor constructs a FileWriter object when a file object is given. FileWriter(File file, boolean append) It constructs an object for Filewriter. FileWriter(FileDescriptor fd) Constructs a FileWriter object associated using a file descriptor. FileWriter(String fileName) It constructs a FileWriter object when a file name is given. public void write(int c) throws IOException It writes a single character. public void write(char[] stir) throws IOException It writes an array of character. public void write(String str) throws IOException It writes a string in Java. FileWriter(String filename, Boolean append) It constructs a FileWriter object when a file name is present. public void write(String str, int off, int len) throws IOException It writes a portion of a String. Conclusion: This article would have helped you in knowing various details about file handling in Java. You can now create your own file and perform various file handling operations to it. This lets you store the data and retrieve them easily.