CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Working with Files and Directories in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

Working with Files and Directories in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

Files and directories are a fundamental part of any operating system, and Java provides several ways to interact with them. In this blog post, we’ll take a look at how to work with files and directories in Java, including how to read and write to files, how to create, delete, and list directories, and how to check for the existence of a file or directory.

Table of Contents

Read contents from file in Java
Create file in Java
Create directory in Java
Delete directory in Java
List directory to see content in Java
Check file existence in Java

Read contents from file in Java

To read from a file, we can use the BufferedReader class. Let’s see the code to read the contents of a file line by line below:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        // Create a BufferedReader to read from a file
        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            // Read each line from the file
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Create file in Java

To write a file, we can use the BufferedWriter class.

Let’s see an example of how to write a string to a file:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        // Create a BufferedWriter to write to a file
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
            // Write a string to the file
            bw.write("Hello, world!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Create directory in Java

To create a new directory, we can use the mkdir() method of the File class. This method creates a single directory and returns a boolean indicating whether the directory was successfully created.

Following is an example of how to use mkdir():

import java.io.File;

public class Main {
    public static void main(String[] args) {
        // Create a new directory
        File dir = new File("newdir");
        if (dir.mkdir()) {
            System.out.println("Directory created");
        } else {
            System.out.println("Directory not created");
        }
    }
}

Delete directory in Java

To delete a directory, we can use the delete() method of the File class. This method deletes a single directory and returns a boolean indicating whether the directory was successfully deleted.

Following is an example of how to use delete():

import java.io.File;

public class Main {
    public static void main(String[] args) {
        // Delete a directory
        File dir = new File("newdir");
        if (dir.delete()) {
            System.out.println("Directory deleted");
        } else {
            System.out.println("Directory not deleted");
        }
    }
}

List directory to see content in Java

To list the contents of a directory, we can use the list() method of the File class. This method returns an array of strings containing the names of the files and directories in the given directory.

Following is an example of how to use list():

import java.io.File;

public class Main {
    public static void main(String[] args) {
        // List the contents of a directory
        File dir = new File(".");
        String[] contents = dir.list();
        for (String s : contents) {
            System.out.println(s);
        }
    }
}

Check file existence in Java

We can use the exists() method of the File class to check for the existence of a file or directory. This method returns a boolean indicating whether the file or directory exists.

Example of how to use exists():

import java.io.File;

public class Main {
    public static void main(String[] args) {
        // Check for the existence of a file
        File file = new File("file.txt");
        if (file.exists()) {
            System.out.println("File exists");
        } else {
            System.out.println("File does not exist");
        }
    }
}

In this blog post, we looked at how to work with files and directories in Java. We saw how to read and write to files, how to create, delete, and list directories, and how to check for the existence of a file or directory. With these techniques, you should be able to easily work with files and directories in your Java programs.

Related Posts:

  • MySQL Commands for Developers
  • Control Statements in Java
  • What is Java? Exploring Its Key Features, Benefits,…
  • Install and Set Up Java Development Environment
  • What Is Java Swing? A Complete Guide to Java’s GUI Toolkit
  • Identifiers in Java
Tags:javalanguage-fundamentals
Was this article helpful?
← Previous ArticleFinal Class in Java: Enforcing Immutability and Security
Next Article →Byte Stream in Java

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap