[go: up one dir, main page]

0% found this document useful (0 votes)
10 views13 pages

Chapter 6

Uploaded by

mmhj6470
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views13 pages

Chapter 6

Uploaded by

mmhj6470
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter- 6

File Handling in Java

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 1
0132130807
Introduction of File handling
• File handling in Java allows you to create, read, update, and
delete files on the file system.
• Java provides various classes and methods in the `java.io` and
`java.nio.file` packages to facilitate these operations.
• In programming languages, file handling typically
involves opening a file, performing read or write
operations on the file, and then closing the file once
the operations are completed.
• This ensures that the data is properly saved and the
file resources are released.
• File handling is essential for tasks such as reading
configuration files, saving user data, logging
information, and processing large datasets

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 2
0132130807
Key Topics of File Handling
1. **File Class** - Represents a file or directory path in the file system.

2. **FileReader and FileWriter**- Used for reading from and writing to text files.

3. **BufferedReader and BufferedWriter**- Provide buffering for reading and writing,


improving performance.

4. **PrintWriter** - Provides convenient methods to write formatted text to files.

5. **FileInputStream and FileOutputStream**- Used for reading and writing binary files.

6. **Serialization** - Converting an object into a byte stream for saving to a file.

7. **NIO (New Input/Output)**- Introduces classes like `Path`, `Files` for advanced file operation.
File class
In Java, the File class is used to represent file and directory paths in the file system. This
class is part of the java.io package and provides methods to interact with files and
directories. Here is a brief overview of the File class in Java:
•Creation: You can create a File object by providing a file path or a directory path as a
string:
File file = new File("path/to/file.txt");
•File Operations: The File class provides methods to perform various file operations such
as checking if a file exists, creating a new file, deleting a file, getting file information, etc.
•File file = new File("path/to/file.txt");
•// Check if the file exists
boolean fileExists = file.exists(); file.exists();
•Directory Operations: You can also use the File class to perform operations on directories
such as listing files in a directory, creating a new directory, deleting a directory, etc
File directory = new File("path/to/directory"); // List files in a directory
String[] filesInDirectory = directory.list();
•File Path Manipulation: The File class provides methods to manipulate file paths, such as
getting the parent directory, checking if a path is a directory, etc.
boolean isDirectory = file.isDirectory();
•The File class in Java is a versatile class that allows you to work with files and directories in
a platform-independent way. It is commonly used for file handling operations in Java
applications.
Using the File Class java example
import java.io.File;

public class FileExample


{
public static void main(String[] args)
{
File file = new File("example.txt");
// Check if the file exists
if (file.exists()) {
System.out.println("File exists.");
}
else {
System.out.println("File does not exist.");
}
}
}
FileReader and FileWriter classes
In Java, FileReader and FileWriter classes are used for reading and writing
character data from and to files, respectively.These classes are used for
text files and are built on top of
the InputStreamReader and OutputStreamWriterclasses, providing convenient
methods for handling character-based input and output.

FileReader
•Reading from Files: FileReader is used to read character data from files.
It reads data from a file one character at a time.
Closing the Reader: It's important to close the FileReader once you're
done with it to release system resources.
FileWriter
•Writing to Files: FileWriter is used to write character data to files. It
writes data to a file one character at a time.
Flushing and Closing: It's important to flush and close the FileWriter to
ensure that all data is written to the file and to release system resources.
Using BufferedReader and BufferedWriter
For better performance when reading and writing text files, it's common to
use BufferedReader and BufferedWriter in combination
Reading from a File using FileReader and BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {


public static void main(String[] args)
{
String filePath = "example.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing to a File using FileWriter and BufferedWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {


public static void main(String[] args) {
String filePath = "example.txt";

try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {


bw.write("Hello, World!");
bw.newLine();
bw.write("Welcome to file handling in Java.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
PrintWriter
In Java, PrintWriter is a class that provides convenient methods for writing
formatted text to a file. It is often used for writing character data to text
files. PrintWriter is built on top of Writer and OutputStreamWriter classes,
allowing for easy writing of text data to files.
Here's an overview of how to use PrintWriter in Java:
Writing Text to a File with PrintWriter
You can create a PrintWriter object by passing a file name or a File object to its
constructor. You can then use methods like print, println, and printf to write
formatted text to the file.
Appending to an Existing File
You can also create a PrintWriter that appends text to an existing file by
passing a second parameter with the value true to the constructor.
Closing the PrintWriter
It's good practice to close the PrintWriter once you are done with it to ensure
that all data is flushed and the file resources are released properly.
Exception Handling
Remember to handle any potential IOException that may occur during file
operations to gracefully manage errors.
PrintWriter in Java is a useful class for writing character data to files in a
Using PrintWriter to Write to a File in java
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class PrintWriterExample {


public static void main(String[] args) {
String filePath = "example.txt";

try (PrintWriter pw = new PrintWriter(filePath)) {


pw.println("Printing to a file using PrintWriter.");
pw.printf("Number: %d, String: %s%n", 10, "Java");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
FileInputStream and FileOutputStream
In Java, FileInputStream and FileOutputStream are classes used for reading and
writing binary data from and to files, respectively. These classes are used for
operations on binary files, which can include images, audio files, video files, and any
other type of non-text files.
Here's an overview of how to use FileInputStream and FileOutputStream in Java:
FileInputStream
•Reading from Files: FileInputStream is used to read binary data from files. It reads
data from a file byte by byte.
•Closing the Stream: It's important to close the FileInputStream once you are
finished reading from the file to release system resources.
FileOutputStream
•Writing to Files: FileOutputStream is used to write binary data to files. It writes data
to a file byte by byte.
•Flushing and Closing: It's important to flush and close the FileOutputStream to
ensure that all data is written to the file and to release system resources.
Using Buffered Streams for Better Performance
For better performance when reading and writing binary files, you can
use BufferedInputStream and BufferedOutputStream in combination
with FileInputStream and FileOutputStream:
Reading and Writing Binary Files using FileInputStream and
FileOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BinaryFileExample {
public static void main(String[] args) {
String filePath = "data.bin";
// Writing binary data
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(65); // Writing the ASCII value of 'A'
fos.write(66); // Writing the ASCII value of 'B'
} catch (IOException e) {
e.printStackTrace();
}
// Reading binary data
try (FileInputStream fis = new FileInputStream(filePath)) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data); // Convert to character and print
}
} catch (IOException e)
{e.printStackTrace();
}
}
Any
Questions?

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
0132130807

You might also like