SlideShare a Scribd company logo
1 of 19
Download to read offline
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

More Related Content

What's hot

Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
Mp3 player project presentation
Mp3 player project presentationMp3 player project presentation
Mp3 player project presentationAntonio Mondragon
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAMehak Tawakley
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Web servers – features, installation and configuration
Web servers – features, installation and configurationWeb servers – features, installation and configuration
Web servers – features, installation and configurationwebhostingguy
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web DevelopmentRobert J. Stein
 
Adrotator in asp
Adrotator in aspAdrotator in asp
Adrotator in aspSireesh K
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databasePayal Dungarwal
 
Debugging Modern C++ Application with Gdb
Debugging Modern C++ Application with GdbDebugging Modern C++ Application with Gdb
Debugging Modern C++ Application with GdbSenthilKumar Selvaraj
 
Php famous built in functions
Php   famous built in functionsPhp   famous built in functions
Php famous built in functionsMaaz Shamim
 
Linux Administration
Linux AdministrationLinux Administration
Linux AdministrationHarish1983
 
Linux.ppt
Linux.ppt Linux.ppt
Linux.ppt onu9
 

What's hot (20)

Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Mp3 player project presentation
Mp3 player project presentationMp3 player project presentation
Mp3 player project presentation
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java Swing
Java SwingJava Swing
Java Swing
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Web servers – features, installation and configuration
Web servers – features, installation and configurationWeb servers – features, installation and configuration
Web servers – features, installation and configuration
 
NodeJS
NodeJSNodeJS
NodeJS
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Linux commands
Linux commandsLinux commands
Linux commands
 
Jsp
JspJsp
Jsp
 
Adrotator in asp
Adrotator in aspAdrotator in asp
Adrotator in asp
 
Dynamic web pages in java
Dynamic web pages in javaDynamic web pages in java
Dynamic web pages in java
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 
Debugging Modern C++ Application with Gdb
Debugging Modern C++ Application with GdbDebugging Modern C++ Application with Gdb
Debugging Modern C++ Application with Gdb
 
Php famous built in functions
Php   famous built in functionsPhp   famous built in functions
Php famous built in functions
 
Linux Administration
Linux AdministrationLinux Administration
Linux Administration
 
Linux.ppt
Linux.ppt Linux.ppt
Linux.ppt
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 

Similar to File Handling in Java.pdf

Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptxcherryreddygannu
 
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
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.ioNilaNila16
 
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.docxalfred4lewis58146
 
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
 
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
 
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
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 

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
 
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
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
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
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
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
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
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
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 

More from SudhanshiBakre1

Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdfSudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdfSudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
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
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
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
 
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
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
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
 
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
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
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
 
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
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
 

Recently uploaded

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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.