Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

java-File-Handling

The document provides an overview of file handling in Java, detailing the use of the File class and various input/output stream classes such as PrintWriter, BufferedReader, and FileReader. It explains how to create, read, and write files, as well as methods for managing file operations, including creating a BufferedReader and using methods like read(), readLine(), and close(). Additionally, it covers file information retrieval, deletion, and listing files in a directory.

Uploaded by

jazztice13jay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java-File-Handling

The document provides an overview of file handling in Java, detailing the use of the File class and various input/output stream classes such as PrintWriter, BufferedReader, and FileReader. It explains how to create, read, and write files, as well as methods for managing file operations, including creating a BufferedReader and using methods like read(), readLine(), and close(). Additionally, it covers file information retrieval, deletion, and listing files in a directory.

Uploaded by

jazztice13jay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

File Handling in Java

Lesson 12
1. File handling is an important part of any application.
2. The File class from the java.io package, allows us to
work with files.
3. To use the File class, create an object of the class,
and specify the filename or directory name.
Files
• Files are stored on disks
• Each files consist of multiple lines composed of
characters
• Each line ends with an end of line character
• The file itself may have an end of file character
• Programmers often need to read or write files stored
on disks
Streams
• Stream: an object that either delivers data to its destination (screen, file,
etc.) or that takes data from a source (keyboard, file, etc.)
– it acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program
– System.in is an input stream
• Output stream: a stream that accepts output from a program
– System.out is an output stream
• A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
Text File I/O
• Important classes for text file output (to the file)
– PrintWriter
– FileOutputStream [or FileWriter]
• Important classes for text file input (from the file):
– BufferedReader
– FileReader
• FileOutputStream and FileReader take file names as arguments.
• PrintWriter and BufferedReader provide useful methods for easier writing
and reading.
• Usually need a combination of two classes
• To use these classes your program needs a line like the following:
• import java.io.*;
• Java File class represents the files and directory
pathnames in an abstract manner.
• This class is used for creation of files and
directories, file searching, file deletion, etc.
• The File object represents the actual file/directory
on the disk.
File Class Methods
Java Create and Write to Files
• To create a file in Java, you can use the createNewFile()
method.
• This method returns a boolean value: true if the file was
successfully created, and false if the file already exists.
• Note that the method is enclosed in a try...catch block.
• This is necessary because it throws an IOException if an
error occurs (if the file cannot be created for some
reason):
Java File Operation Method
Creating a File
Writing File to a Specific Directory
• To create a file in a specific directory (requires permission), specify
the path of the file and use double backslashes to escape the "\"
character (for Windows).
• On Mac and Linux you can just write the path, like:
/Users/name/filename.txt

File myObj = new File("C:\\Users\\MyName\\filename.txt");


Write to a File
• In the following
example, we use the
FileWriter class
together with its write()
method to write some
text to the file we
created in the example
above.
• Note that when you are
done writing to the file,
you should close it with
the close() method:
Read a File
• In the following
example, we use the
Scanner class to read
the contents of the
text file.
Read a File with BufferedReader
• The BufferedReader class of the java.io package can be used with
other readers to read data (in characters) more efficiently.
• It extends the abstract class Reader.
Working of BufferedReader
• The BufferedReader maintains an internal buffer of 8192 characters.
• The buffer will help to read characters from the files more quickly.
• During the read operation in BufferedReader, a chunk of characters is
read from the disk and stored in the internal buffer. And from the
internal buffer characters are read individually.
• Hence, the number of communication to the disk is reduced. This is
why reading characters is faster using BufferedReader.
• To open a text file for input: connect a text file to a stream for reading

– a BufferedReader object uses FileReader to open a text file

– FileReader “connects” BufferedReader to the text file

• For example:

• FileReader s = new FileReader(“input.txt");


• BufferedReader inStream = new BufferedReader(s);
Create a BufferedReader
• In order to create a BufferedReader, we must import the
java.io.BuferedReader package first. Once we import the package, here is
how we can create the reader.

• In the above example, we have created a BufferedReader named buffer


with the FileReader named file.
• Here, the internal buffer of the BufferedReader has the default size of 8192
characters. However, we can specify the size of the internal buffer as well.
Methods of BufferedReader
The BufferedReader class provides implementations for different
methods present in Reader.

• read() - reads a single character from the internal buffer of the reader
• read(char[] array) - reads the characters from the reader and stores in
the specified array
• read(char[] array, int start, int length) - reads the number of
characters equal to length from the reader and stores in the specified
array starting from the position start
Methods of BufferedReader
• read: read a char at a time
• readLine: read a line into a String
• close: close BufferedReader stream
Example
Example Cont…
• In this example, we have created
a buffered reader named input.
The buffered reader is linked
with the input.txt file.

• Here, we have used the read()


method to read an array of
characters from the internal
buffer of the buffered reader.
Skip() Method
• To discard and skip the
specified number of
characters, we can use the
skip() method.
• In this example, we have
used the skip() method to
skip 5 characters from the file
reader. Hence, the characters
'T', 'h', 'i', 's' and ' ' are
skipped from the original file.
Close() Method
To close the buffered reader, we can use the close() method. Once the
close() method is called, we cannot use the reader to read the data.
Getting File Information
• To get more
information about a
file, use any of the File
methods:
Deleting a File
Listing all files in a Folder
import java.io.File;
abc.class
abc.java
AgeCalculator. lass

public class ListFilesinFolder AgeCalculator.j


ascii.class
ascii.java
ava

{ CheckEvenOdd
CheckEvenOdd
comsats.class
.class
.java

public static void main(String[] args) comsats.java


CountFilesinFol der.class
CountFilesinFol der.java
{ CreateFile.class
CreateFile.java
DiceRoller.class
int count=0; DiceRoller.java
Dog.class

// creates a file object example1.class


example1.java
ExampleThrows .class

File file = new File("C:\\Users\\mikez\\Desktop\\JAVA"); ExampleThrows


exceptions.clas
exceptions.java
.java s

Factorial.class
Factorial.java
filename.txt
// returns an array of all files String[] GradeBook.java
GradeBookTes t.java
hs_err_pid3692 .log
fileList = file.list(); hs_err_pid3832
hs_err_pid4136
.log
.log
jadoon.java
khan.java
lab.class

for(String str : fileList) lab.java


Movieshop.clas
Movieshop.java
s

{ MyClass.class
MyClass.java
Pet.class
System.out.println(str); count++; RefVarofTypeI
RefVarofTypeI
terface.class
terface.java
RollDie.class
RollDie.java
s1.class

} s1.java
Student.class
StudentTest.clas s

System.out.println(“Total Files:” +count); StudentTest.jav


WriteToFile.clas
WriteToFile.java
a s

} xyz.class xyz.java
Total Files: 53
}
FileInputStream
• A FileInputStream obtains input bytes from a file in a file
system.
• What files are available depends on the host environment.
• FileInputStream is meant for reading streams of raw bytes
such as image data.
• For reading streams of characters, consider using FileReader.
Counting Number of Characters in a File
Counting Number of Characters in a File(Cont…)
Counting Number of Characters in a File(Cont…)

Output

You might also like