Contents
File Handling
Java.io.File Class in Java
Java’s File
class represents the pathname of a file or directory. Since file systems vary across platforms, using a simple string is not enough to handle file or directory names. The File
class provides various methods to work with pathnames, such as deleting or renaming files, creating new directories, listing directory contents, and checking file or directory properties.
Key Features of the File
Class
The File
class acts as an abstract representation of file and directory pathnames. The pathname can either be absolute or relative, and you can obtain the parent directory by calling the getParent()
method. An instance of the File
class is immutable; once created, the pathname it represents doesn’t change.
The file system can impose certain access restrictions like read, write, or execute permissions on files or directories, referred to as access permissions.
How to Create a File
Object
A File
object is created by passing a string representing a file or directory name. You can use either a string or another File
object. For example:
File file = new File("/home/user/docs/myfile.txt");
This creates a File
object representing the myfile.txt
file in the /home/user/docs
directory.
Fields in the File
Class
Field | Type | Description |
---|---|---|
pathSeparator | String | String used to separate paths in a file system. |
pathSeparatorChar | char | Character used to separate paths in a file system. |
separator | String | Default name separator character, represented as a string. |
separatorChar | char | Default name separator character. |
Constructors of the File
Class
Methods of the File
Class
1. File(File parent, String child): Creates a File instance from a parent directory and a child pathname.
2. File(String pathname): Creates a File instance from a string pathname.
3. File(String parent, String child): Creates a File instance from a parent directory string and a child pathname.
4. File(URI uri): Creates a File instance from a URI object.
Method | Description | Return Type |
---|---|---|
canExecute() | Checks if the file can be executed. | boolean |
canRead() | Checks if the file can be read. | boolean |
canWrite() | Checks if the file can be written to. | boolean |
compareTo(File pathname) | Compares two pathnames lexicographically. | int |
createNewFile() | Atomically creates a new empty file. | boolean |
delete() | Deletes the file or directory. | boolean |
exists() | Checks if the file or directory exists. | boolean |
getAbsolutePath() | Returns the absolute pathname string. | String |
list() | Returns an array of names of files and directories. | String[] |
getFreeSpace() | Returns the number of unallocated bytes in the partition. | long |
getName() | Returns the name of the file or directory. | String |
isDirectory() | Checks if the pathname is a directory. | boolean |
isFile() | Checks if the pathname is a regular file. | boolean |
isHidden() | Checks if the file is hidden. | boolean |
length() | Returns the length of the file in bytes. | long |
mkdir() | Creates a new directory. | boolean |
renameTo(File dest) | Renames the file or directory. | boolean |
toString() | Returns the string representation of the pathname. | String |
toURI() | Returns a URI representing the pathname. | URI |
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Example 1: Check if a File or Directory Exists
This program takes a filename or directory name as input, then checks if the file or directory exists and displays its properties.
import java.io.File;
class FileProperties {
public static void main(String[] args) {
String filename = args[0];
File file = new File(filename);
System.out.println("File Name: " + file.getName());
System.out.println("Path: " + file.getPath());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Parent: " + file.getParent());
System.out.println("Exists: " + file.exists());
if (file.exists()) {
System.out.println("Writable: " + file.canWrite());
System.out.println("Readable: " + file.canRead());
System.out.println("Is Directory: " + file.isDirectory());
System.out.println("File Size (bytes): " + file.length());
}
}
}
Output:
File Name: file.txt
Path: file.txt
Absolute Path: /home/user/file.txt
Parent: null
Exists: true
Writable: true
Readable: true
Is Directory: false
File Size (bytes): 100
Example 2: Display Directory Contents
This program accepts a directory path from the user and lists its contents.
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class DirectoryContents {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter directory path:");
String dirPath = br.readLine();
File dir = new File(dirPath);
if (dir.exists() && dir.isDirectory()) {
String[] contents = dir.list();
System.out.println("Contents of " + dirPath + ":");
for (String item : contents) {
File f = new File(dirPath, item);
if (f.isFile()) {
System.out.println(item + " (File)");
} else if (f.isDirectory()) {
System.out.println(item + " (Directory)");
}
}
} else {
System.out.println("Directory not found.");
}
}
}
Output:
Enter directory path:
/home/user/docs
Contents of /home/user/docs:
file1.txt (File)
file2.txt (File)
subfolder (Directory)
Java Program to Create a New File
Steps to Create a New File in Java
1. First Step: To create a new file in Java, we need to handle any potential exceptions properly. This is important because the file operations may throw exceptions. We will be using Java’s try-catch block for this purpose, which is one of the standard ways to handle exceptions.
2. Second Step: Next, we will import the File
class, which is required to work with files in Java.
Example to create a File
object:
File fileObject = new File(directoryPath);
Methods to Create a New File in Java
There are two main ways to create a file in Java:
1. Using the File
class.
2. Using the FileOutputStream
class.
These classes provide a variety of methods for performing file operations such as creating files, checking if a file exists, and more.
Let’s now look at examples of both approaches.
Example 1: Creating a File Using the File
Class
In this approach, we use the File
class to create a new file. This class represents an abstract path and allows us to work with the file without requiring its physical existence until necessary.
Code Example:
// Import necessary libraries
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class FileCreator {
public static void main(String[] args) {
// Creating a new file using a custom method
FileCreator creator = new FileCreator();
creator.createNewFile();
}
// Method to create a new file
public void createNewFile() {
String filePath = "", fileName = "";
// Use try-catch block to handle exceptions
try {
// Using BufferedReader to take user input for file name and path
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the file name:");
// Reading the file name from user input
fileName = reader.readLine();
System.out.println("Please enter the directory path:");
// Reading the file path from user input
filePath = reader.readLine();
// Creating a new File object with the provided file name and path
File file = new File(filePath + "/" + fileName + ".txt");
// Method to create a new blank file
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Please enter the file name:
newFile
Please enter the directory path:
/Users/username/Desktop/Folder
File created: newFile.txt
Explanation:
- The program prompts the user to enter a file name and directory path.
- It uses the
createNewFile()
method from theFile
class to create the file. - If the file is successfully created, it outputs the file name and path.
public static void main(String[] args) {
// program logic
}
Example 2: Creating a File Using the FileOutputStream
Class
Another way to create a file in Java is by using the FileOutputStream
class. This class is used to write data to a file, and it can also be used to create a new file if one doesn’t already exist.
Code Example:
// Import necessary libraries
import java.io.FileOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class FileCreator {
public static void main(String[] args) {
// Creating a new file using a custom method
FileCreator creator = new FileCreator();
creator.createNewFileWithStream();
}
// Method to create a new file using FileOutputStream
public void createNewFileWithStream() {
String filePath = "", fileName = "";
// Use try-catch block to handle exceptions
try {
// Using BufferedReader to take user input for file name and path
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the file name:");
// Reading the file name from user input
fileName = reader.readLine();
System.out.println("Please enter the directory path:");
// Reading the file path from user input
filePath = reader.readLine();
// Creating a new FileOutputStream object with the provided file name and path
FileOutputStream fos = new FileOutputStream(filePath + "/" + fileName + ".txt");
System.out.println("File created using FileOutputStream.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Please enter the file name:
newFile
Please enter the directory path:
/Users/username/Desktop/Folder
File created using FileOutputStream.
Java Program to Write into a File
In Java, several classes and methods are available to write data into files. The FileWriter
class is commonly used for writing character-oriented data into files, and it plays a crucial role in Java’s file handling system. This article will discuss multiple ways to write data into a file using Java.
Methods to Write into a File in Java:
1. Using writeString() Method
2. Using FileWriter Class
3. Using BufferedWriter Class
4. Using FileOutputStream Class
Method 1: Using writeString()
Method
Introduced in Java 11, the writeString()
method allows writing text into a file. It requires the file path and character sequence as mandatory parameters. This method is simple and useful when the file content is relatively small.
Example:
// Import required classes
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileWriteExample {
public static void main(String[] args) {
// Define content to be written
String content = "Hello, Java File Handling\nLet's write to a file!";
// Define the path of the file
Path filePath = Path.of("output.txt");
try {
// Write content to the file
Files.writeString(filePath, content);
// Read and print the content from the file
String fileContent = Files.readString(filePath);
System.out.println(fileContent);
} catch (IOException e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Output:
Hello, Java File Handling
Let's write to a file!
Method 2: Using FileWriter
Class
FileWriter
writes a stream of characters into a file. It’s ideal for smaller content. The following example demonstrates how to use the FileWriter
class to write data to a file.
Example:
// Import necessary classes
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
// Content to write into the file
String content = "Learning Java File Handling.";
try {
// Create FileWriter object
FileWriter writer = new FileWriter("example.txt");
// Write content to the file
writer.write(content);
// Print content
System.out.println("Content written: " + content);
// Close the writer
writer.close();
System.out.println("File has been written successfully.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Content written: Learning Java File Handling.
File has been written successfully.
Method 3: Using BufferedWriter
Class
The BufferedWriter
class provides better performance when writing larger content because it uses a buffer to write text efficiently. It is recommended for writing large files.
Example:
// Import necessary classes
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample {
public static void main(String[] args) {
// Content to write
String content = "Buffered Writer in Java\nOptimized for large content.";
try {
// Create BufferedWriter object
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("buffered_output.txt"));
// Write content to file
bufferedWriter.write(content);
// Print the content
System.out.println("Content written: " + content);
// Close the writer
bufferedWriter.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Content written: Buffered Writer in Java
Optimized for large content.
File written successfully.
Delete a File Using Java
In Java, files can be permanently deleted using various methods, and unlike traditional delete operations in operating systems, these files do not go to the recycle bin or trash. Below is the method available in Java for deleting files.
Using java.io.File.delete()
Method
The delete()
method of the File
class can be used to delete files or directories. It returns true
if the file or directory is successfully deleted, and false
otherwise.
Syntax:
public boolean delete()
Returns:
true
if the file or directory is deleted successfully.false
if the file or directory cannot be deleted.
Example:
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
// Creating a file object
File file = new File("example.txt");
// Deleting the file
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}
Output:
File deleted successfully.
File Permissions in Java
Java File Permission Management
Java offers several methods to check and modify file permissions, which can be useful when restricting or allowing certain file operations. For instance, a file that is read-only can be updated to allow write operations or vice versa.
Checking Current File Permissions
A file in Java can be in any of the following permission states, and these can be checked using specific methods from the File
class.
Method | Action Performed |
---|---|
canExecute() | Returns true if the file is executable and the application has permission to execute the file. |
canRead() | Returns true if the file is readable. |
canWrite() | Returns true if the file is writable and the application has permission to write to the file. |
Example:
This Java program demonstrates how to check a file’s current permissions (readable, writable, executable).
import java.io.File;
public class FilePermissionCheck {
public static void main(String[] args) {
// Create a file object
File file = new File("sample.txt");
// Check if the file exists
if (file.exists()) {
// Display current file permissions
System.out.println("Executable: " + file.canExecute());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
} else {
System.out.println("File not found.");
}
}
}
Output:
Executable: false
Readable: true
Writable: true
Changing File Permissions
Java provides several methods to alter file permissions for readability, writability, and executability.
Method | Action Performed |
---|---|
setExecutable() | Sets the execute permission for the file. |
setReadable() | Sets the read permission for the file. |
setWritable() | Sets the write permission for the file. |
Note:
- The
setReadable()
andsetWritable()
methods may fail if the underlying file system does not support changing permissions or if the user lacks appropriate privileges.
Example:
This program shows how to change a file’s permissions using Java methods.
import java.io.File;
public class FilePermissionModify {
public static void main(String[] args) {
// Create a file object
File file = new File("document.txt");
// Check if the file exists
if (file.exists()) {
// Modify the file permissions
file.setExecutable(true);
file.setReadable(true);
file.setWritable(false);
System.out.println("File permissions changed.");
// Display updated permissions
System.out.println("Executable: " + file.canExecute());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
} else {
System.out.println("File not found.");
}
}
}
Output:
File permissions changed.
Executable: true
Readable: true
Writable: false
FileWriter Class in Java
Java FileWriter
Class Overview
The Java FileWriter
class, part of the java.io
package, is used to write data in character format to files. It is designed for handling character-based input/output and extends the OutputStreamWriter
class, which in turn inherits from the Writer
class.
Hierarchy of Java FileWriter
Class
FileWriter
extends theOutputStreamWriter
andWriter
classes.- It implements the
Closeable
,Flushable
,Appendable
, andAutoCloseable
interfaces.
The FileWriter
class creates the output file if it doesn’t already exist. It is specifically meant for character-based writing. If you need to write raw bytes, the FileOutputStream
class should be used instead.
Constructors of FileWriter
Class
1. FileWriter(File file): Creates a FileWriter
object using a File
object.
FileWriter fw = new FileWriter(new File("myfile.txt"));
2. FileWriter(File file, boolean append): Allows appending to an existing file if append
is true
; otherwise, it overwrites the file.
FileWriter fw = new FileWriter(new File("myfile.txt"), true);
3. FileWriter(FileDescriptor fd): Constructs a FileWriter
using a file descriptor.
FileWriter fw = new FileWriter(FileDescriptor.out);
4. FileWriter(File file, Charset charset): Creates a FileWriter
using a specific file and character set.
FileWriter fw = new FileWriter(new File("myfile.txt"), Charset.forName("UTF-8"));
5. FileWriter(String fileName): Creates a FileWriter
using a file name.
FileWriter fw = new FileWriter("myfile.txt");
6. FileWriter(String fileName, boolean append): Creates a FileWriter
to append or overwrite based on the boolean value.
FileWriter fw = new FileWriter("myfile.txt", true); // append
Example 1: Writing Data to a File
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
String data = "Hello, World!";
try {
FileWriter fw = new FileWriter("example.txt");
fw.write(data);
System.out.println("Data written successfully.");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Data written successfully.
The file example.txt
will contain the text: Hello, World!
.
Overwriting vs Appending to a File
Overwrite: When a file is created using a constructor with only the file name, any existing data in the file will be replaced.
FileWriter fw = new FileWriter("output.txt"); // overwrites
- Append: To append data to an existing file, a second parameter
true
is passed.
FileWriter fw = new FileWriter("output.txt", true); // appends
Example : Appending Data to a File
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileExample {
public static void main(String[] args) {
String newData = " Welcome back!";
try {
FileWriter fw = new FileWriter("example.txt", true); // appending
fw.write(newData);
System.out.println("Data appended successfully.");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Data appended successfully.
Basic Methods of FileWriter
Class
1. write(int a): Writes a single character.
fw.write(65); // writes 'A' (ASCII value)
2. write(char[] cbuf): Writes an array of characters.
char[] data = {'H', 'i'};
fw.write(data);
3. write(String str): Writes a string to the file.
fw.write("Hello");
Example 4: Getting Encoding
The getEncoding()
method retrieves the character encoding used by the FileWriter
.
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.io.IOException;
public class EncodingExample {
public static void main(String[] args) {
try {
FileWriter fw1 = new FileWriter("output1.txt");
FileWriter fw2 = new FileWriter("output2.txt", Charset.forName("UTF-8"));
System.out.println("Encoding of fw1: " + fw1.getEncoding());
System.out.println("Encoding of fw2: " + fw2.getEncoding());
fw1.close();
fw2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Encoding of fw1: Cp1252
Encoding of fw2: UTF-8
Java.io.FileDescriptor in Java
java.io.FileDescriptor
The java.io.FileDescriptor
class represents an opaque handle to machine-specific structures such as open files, sockets, or other byte streams. Its main use is to be passed to a FileInputStream
or FileOutputStream
for reading or writing data. Instances of this class should not be created by applications directly, as Java handles the underlying system details.
The FileDescriptor class offers several useful methods and fields for interacting with files and streams, including handles to the standard input, output, and error streams.
Fields:
- err: Handle for the standard error stream.
- in: Handle for the standard input stream.
- out: Handle for the standard output stream.
Declaration:
public final class FileDescriptor
extends Object
Methods:
1. sync():
This method ensures that all the data in the file descriptor’s buffers is written to the actual device. It is especially useful for making sure that written data is saved immediately.
Syntax:
public void sync()
2. Return Type: void
Exception: SyncFailedException
: Thrown if synchronization cannot be guaranteed.
Example for sync()
method:
import java.io.*;
public class SyncExample {
public static void main(String[] args) throws IOException {
FileDescriptor fileDescriptor = null;
FileOutputStream fileOut = null;
byte[] data = {65, 66, 67, 68}; // ASCII for 'ABCD'
try {
fileOut = new FileOutputStream("output.txt");
fileDescriptor = fileOut.getFD();
fileOut.write(data);
// Synchronize data with the underlying device
fileDescriptor.sync();
System.out.println("Data synced successfully.");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOut != null) {
fileOut.close();
}
}
}
}
Output:
Data synced successfully.
After running the above code, the file output.txt
will contain the text:
ABCD
3. valid(): The valid()
method checks if a FileDescriptor
is valid.
Syntax:
public boolean valid()
4. Return Type:
- true: If the file descriptor is valid.
- false: If it is invalid.
Example:
import java.io.*;
public class ValidExample {
public static void main(String[] args) throws IOException {
FileDescriptor fileDescriptor = null;
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream("output.txt");
fileDescriptor = fileIn.getFD();
// Check if the FileDescriptor is valid
boolean isValid = fileDescriptor.valid();
System.out.println("FileDescriptor valid: " + isValid);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileIn != null) {
fileIn.close();
}
}
}
}
Output:
FileDescriptor valid: true
Related Chapters
- Overview
- Basic Concepts
- Input/Output in Java
- Flow Control in Java
- Operators in Java
- Arrays
- OOPS in Java
- Inheritance
- Abstraction
- Encapsulation
- Polymorphism
- Constructors
- Methods
- Interfaces
- Memory Allocation
- Wrapper Classes
- Keywords
- Access Modifiers
- Classes in java
- Packages in Java
- Exceptions in Java
- Multithreading in Java
- Synchronization in Java
- File Handling