[Go to site: main page, start]

0% found this document useful (0 votes)
11 views11 pages

Java File Operations Guide

The document provides an overview of file handling in Java, detailing operations such as creating, reading, writing, and deleting files using the java.io.File class and the java.nio.file package. It includes code examples for various file operations, including using byte and character streams, and advanced techniques like FileChannel and memory-mapped files. Additionally, it lists methods available in the File class for managing file attributes and operations.

Uploaded by

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

Java File Operations Guide

The document provides an overview of file handling in Java, detailing operations such as creating, reading, writing, and deleting files using the java.io.File class and the java.nio.file package. It includes code examples for various file operations, including using byte and character streams, and advanced techniques like FileChannel and memory-mapped files. Additionally, it lists methods available in the File class for managing file attributes and operations.

Uploaded by

adiyaguptamlg
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link]

com/in/kunalkr19

File Handling in Java

File Operations in Java


In Java, a File is an abstract data type. A named location used to store related
information is known as a File. There are several File Operations like creating a
new File, getting information about File, writing into a File, reading from a File
and deleting a File.

Stream

A series of data is referred to as a stream. In Java, Stream is classified into two


types, i.e., Byte Stream and Character Stream.
File Operations in Java
Byte Stream

Byte Stream is mainly involved with byte data. A file handling process with a
byte stream is a process in which an input is provided and executed with the
byte data.

Character Stream

Character Stream is mainly involved with character data. A file handling


process with a character stream is a process in which an input is provided and
executed with the character data.

Basics of File Handling in Java

1. File Class

The [Link] class is used to represent file and directory pathnames in an


abstract manner. It provides methods for creating, deleting, and checking files
and directories, as well as retrieving file metadata.

Creating a File
import [Link];
import [Link];

public class CreateFileExample {


public static void main(String[] args) {
try {
File myFile = new File("[Link]");
if ([Link]()) {
[Link]("File created: " +
[Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]();
}
}
}
This code creates a new file named "[Link]". If the file already exists, it
notifies the user. The createNewFile() method returns true if the file was
created successfully and false if the file already exists. Any IOExceptions
encountered are caught and printed.

Checking if a File or Directory Exists


import [Link];

public class CheckFileExample {


public static void main(String[] args) {
File myFile = new File("[Link]");
if ([Link]()) {
[Link]("File exists.");
} else {
[Link]("File does not exist.");
}
}
}

This code checks whether "[Link]" exists and prints the result. The
exists() method returns true if the file or directory exists, and false
otherwise.

Getting File Information


import [Link];

public class FileInfoExample {


public static void main(String[] args) {
File myFile = new File("[Link]");
if ([Link]()) {
[Link]("File name: " + [Link]());
[Link]("Absolute path: " +
[Link]());
[Link]("Writeable: " + [Link]());
[Link]("Readable: " + [Link]());
[Link]("File size in bytes: " +
[Link]());
} else {
[Link]("The file does not exist.");
}
}
}
This code retrieves and prints various pieces of information about
"[Link]", such as its name, absolute path, readability, writability, and size
in bytes. The length() method returns the size of the file in bytes.

Deleting a File
import [Link];

public class DeleteFileExample {


public static void main(String[] args) {
File myFile = new File("[Link]");
if ([Link]()) {
[Link]("Deleted the file: " +
[Link]());
} else {
[Link]("Failed to delete the file.");
}
}
}

This code deletes "[Link]" if it exists and prints whether the deletion was
successful. The delete() method returns true if the file was deleted
successfully and false otherwise.

2. Reading and Writing Files

Reading Files

Reading files can be done using various classes, such as FileReader and
BufferedReader for character streams and FileInputStream for byte streams.

1. Using FileReader and BufferedReader


import [Link];
import [Link];
import [Link];

public class ReadFileExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads "[Link]" line by line and prints each line using
BufferedReader. The readLine() method reads a line of text, returning null
when the end of the file is reached. Using a BufferedReader wrapped around a
FileReader improves efficiency by buffering input.

2. Using FileInputStream
import [Link];
import [Link];

public class FileInputStreamExample {


public static void main(String[] args) {
try (FileInputStream fis = new
FileInputStream("[Link]")) {
int content;
while ((content = [Link]()) != -1) {
[Link]((char) content);
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads "[Link]" byte by byte and prints the content. The read()
method reads a byte of data, returning -1 when the end of the file is reached.
This method is useful for reading binary files.

Writing Files

Writing files can be done using classes such as FileWriter and BufferedWriter
for character streams and FileOutputStream for byte streams.

1. Using FileWriter and BufferedWriter


import [Link];
import [Link];
import [Link];

public class WriteFileExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new
FileWriter("[Link]"))) {
[Link]("Hello, World!");
[Link]();
[Link]("This is a new line.");
} catch (IOException e) {
[Link]();
}
}
}

This code writes "Hello, World!" and "This is a new line." to "[Link]"
using BufferedWriter. The newLine() method inserts a new line separator.
Using a BufferedWriter wrapped around a FileWriter improves efficiency by
buffering output.

2. Using FileOutputStream
import [Link];
import [Link];

public class FileOutputStreamExample {


public static void main(String[] args) {
try (FileOutputStream fos = new
FileOutputStream("[Link]")) {
String content = "Hello, World!";
[Link]([Link]());
} catch (IOException e) {
[Link]();
}
}
}

This code writes "Hello, World!" to "[Link]" using FileOutputStream. The


write() method writes bytes to the file. This method is useful for writing binary
data.

3. Using [Link] Package

The [Link] package, introduced in Java 7, provides more advanced and


flexible file I/O operations.

Basic Operations

1. Creating and Writing a File


import [Link];
import [Link];
import [Link];
import [Link];

public class NIOWriteFileExample {


public static void main(String[] args) {
Path filePath = [Link]("[Link]");
String content = "Hello, World!";
try {
[Link](filePath, [Link]());
} catch (IOException e) {
[Link]();
}
}
}

This code writes "Hello, World!" to "[Link]" using NIO. The


[Link]() method writes bytes to a file in an efficient manner.

2. Reading a File
import [Link];
import [Link];
import [Link];
import [Link];

public class NIOReadFileExample {


public static void main(String[] args) {
try {
List<String> lines =
[Link]([Link]("[Link]"));
for (String line : lines) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads "[Link]" line by line and prints each line using NIO. The
[Link]() method reads all lines of a file into a List<String>.

4. Advanced File Operations

Using Channels and Buffers


NIO provides FileChannel for efficient file I/O operations. A FileChannel can
be used for reading, writing, mapping, and manipulating files.

1. Reading a File using FileChannel


import [Link];
import [Link];
import [Link];

public class FileChannelReadExample {


public static void main(String[] args) {
try (RandomAccessFile aFile = new
RandomAccessFile("[Link]", "r");
FileChannel inChannel = [Link]()) {
ByteBuffer buffer = [Link](1024);
while ([Link](buffer) > 0) {
[Link]();
while ([Link]()) {
[Link]((char) [Link]());
}
[Link]();
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads "[Link]" using FileChannel and ByteBuffer. The read()
method reads data into the buffer, and the buffer is then flipped for reading data
out.

2. Writing to a File using FileChannel


import [Link];
import [Link];
import [Link];

public class FileChannelWriteExample {


public static void main(String[] args) {
try (RandomAccessFile aFile = new
RandomAccessFile("[Link]", "rw");
FileChannel outChannel = [Link]()) {
String content = "Hello, World!";
ByteBuffer buffer = [Link]([Link]());
[Link](buffer);
} catch (IOException e) {
[Link]();
}
}
}
This code writes "Hello, World!" to "[Link]" using FileChannel and
ByteBuffer. The write() method writes data from the buffer to the file.

Memory-Mapped Files

Memory-mapped files allow you to map a region of a file directly into memory,
providing efficient file access.

1. Reading a Memory-Mapped File


import [Link];
import [Link];
import [Link];
import [Link];

public class MemoryMappedFileReadExample {


public static void main(String[] args) {
try (RandomAccessFile file = new
RandomAccessFile("[Link]", "r");
FileChannel channel = [Link]()) {
MappedByteBuffer buffer =
[Link]([Link].READ_ONLY, 0, [Link]());
for (int i = 0; i < [Link](); i++) {
[Link]((char) [Link]());
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads "[Link]" using a memory-mapped file. The map() method
maps a region of the file directly into memory, and the buffer provides fast
access to the file's content.

2. Writing to a Memory-Mapped File


java
Copy code
import [Link];
import [Link];
import [Link];
import [Link];

public class MemoryMappedFileWriteExample {


public static void main(String[] args) {
try (RandomAccessFile file = new
RandomAccessFile("[Link]", "rw");
FileChannel channel = [Link]()) {
String content = "Hello, World!";
MappedByteBuffer buffer =
[Link]([Link].READ_WRITE, 0, [Link]());
[Link]([Link]());
} catch (IOException e) {
[Link]();
}
}
}

This code writes "Hello, World!" to "[Link]" using a memory-mapped file.


The map() method maps a region of the file directly into memory for fast
writing.

Summary

• Basic Operations: Using [Link] for creating, checking, and


deleting files and directories. The File class provides a simple way to
handle file system operations.
• Reading and Writing Files: Using FileReader, BufferedReader,
FileWriter, BufferedWriter, FileInputStream, and FileOutputStream
for character and byte streams. These classes provide basic mechanisms
for reading and writing text and binary data.
• NIO Package: Using Files class for file operations and Paths for path
manipulation. The NIO package offers more advanced and efficient ways
to handle files.
• Advanced Operations: Using FileChannel for efficient I/O operations
and memory-mapped files for direct memory access. These advanced
techniques provide high performance for large files and complex
operations.

With these tools and techniques, you can efficiently handle files in Java, ranging
from basic file operations to advanced file I/O and memory-mapped file access.

Java File Class Methods

[Link]. Method Return Description


Type
1. canRead() Boolean The canRead() method is used to check whether we can
read the data of the file or not.

2. createNewFile() Boolean The createNewFile() method is used to create a new empty


file.

3. canWrite() Boolean The canWrite() method is used to check whether we can


write the data into the file or not.

4. exists() Boolean The exists() method is used to check whether the specified
file is present or not.

5. delete() Boolean The delete() method is used to delete a file.

6. getName() String The getName() method is used to find the file name.

7. getAbsolutePath() String The getAbsolutePath() method is used to get the absolute


pathname of the file.

8. length() Long The length() method is used to get the size of the file in
bytes.

9. list() String[] The list() method is used to get an array of the files available
in the directory.

10. mkdir() Boolean The mkdir() method is used for creating a new directory.

[Link]

You might also like