WikiGalaxy

Personalize

Java Files - Introduction

Understanding Java Files:

Java provides a robust mechanism to handle files using the java.io package. This package provides classes and interfaces to work with file operations such as reading, writing, and manipulating files.

Creating a File in Java

Creating a New File:

To create a file in Java, you can use the File class. This class provides a method createNewFile() which returns true if the file is created successfully and false if the file already exists.


import java.io.File;
import java.io.IOException;

public class CreateFileExample {
  public static void main(String[] args) {
    File file = new File("example.txt");
    try {
      if (file.createNewFile()) {
        System.out.println("File created: " + file.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}
    

Console Output:

File created: example.txt

Writing to a File

Using FileWriter:

The FileWriter class is used to write characters to a file. It is a part of java.io package and can be used to write strings, characters, and arrays to files.


import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
  public static void main(String[] args) {
    try {
      FileWriter writer = new FileWriter("example.txt");
      writer.write("Hello, World!");
      writer.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}
    

Console Output:

Successfully wrote to the file.

Reading from a File

Using FileReader:

The FileReader class is used to read the contents of a file as a stream of characters. It is a part of java.io package and is efficient for reading character files.


import java.io.FileReader;
import java.io.IOException;

public class ReadFromFileExample {
  public static void main(String[] args) {
    try {
      FileReader reader = new FileReader("example.txt");
      int character;
      while ((character = reader.read()) != -1) {
        System.out.print((char) character);
      }
      reader.close();
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}
    

Console Output:

Hello, World!

Appending to a File

Using FileWriter in Append Mode:

To append content to an existing file, you can use FileWriter with the second parameter set to true. This allows you to add content without overwriting existing data.


import java.io.FileWriter;
import java.io.IOException;

public class AppendToFileExample {
  public static void main(String[] args) {
    try {
      FileWriter writer = new FileWriter("example.txt", true);
      writer.write("\nAppended Text");
      writer.close();
      System.out.println("Successfully appended to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}
    

Console Output:

Successfully appended to the file.

Deleting a File

Using File Class:

The File class provides a method delete() that deletes a file or directory denoted by the abstract pathname. It returns true if the file was successfully deleted.


import java.io.File;

public class DeleteFileExample {
  public static void main(String[] args) {
    File file = new File("example.txt");
    if (file.delete()) {
      System.out.println("Deleted the file: " + file.getName());
    } else {
      System.out.println("Failed to delete the file.");
    }
  }
}
    

Console Output:

Deleted the file: example.txt

Checking File Existence

Using File.exists():

The exists() method of the File class checks whether a file or directory exists at the specified path. It returns true if the file exists.


import java.io.File;

public class CheckFileExistence {
  public static void main(String[] args) {
    File file = new File("example.txt");
    if (file.exists()) {
      System.out.println("The file exists.");
    } else {
      System.out.println("The file does not exist.");
    }
  }
}
    

Console Output:

The file does not exist.

Renaming a File

Using File.renameTo():

The renameTo() method of the File class is used to rename a file. It returns true if the renaming was successful.


import java.io.File;

public class RenameFileExample {
  public static void main(String[] args) {
    File oldFile = new File("oldname.txt");
    File newFile = new File("newname.txt");
    if (oldFile.renameTo(newFile)) {
      System.out.println("File renamed successfully.");
    } else {
      System.out.println("Failed to rename file.");
    }
  }
}
    

Console Output:

File renamed successfully.

Getting File Information

Using File Methods:

The File class provides methods like getName(), getPath(), and length() to retrieve information about a file.


import java.io.File;

public class FileInfoExample {
  public static void main(String[] args) {
    File file = new File("example.txt");
    if (file.exists()) {
      System.out.println("File name: " + file.getName());
      System.out.println("Absolute path: " + file.getAbsolutePath());
      System.out.println("Size: " + file.length() + " bytes");
    } else {
      System.out.println("The file does not exist.");
    }
  }
}
    

Console Output:

File name: example.txt
Absolute path: /path/to/example.txt
Size: 13 bytes

Listing Files in a Directory

Using File.listFiles():

The listFiles() method of the File class returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.


import java.io.File;

public class ListFilesExample {
  public static void main(String[] args) {
    File directory = new File("/path/to/directory");
    File[] filesList = directory.listFiles();
    if (filesList != null) {
      for (File file : filesList) {
        System.out.println("File: " + file.getName());
      }
    } else {
      System.out.println("The directory does not exist or is not a directory.");
    }
  }
}
    

Console Output:

File: file1.txt
File: file2.txt
File: file3.txt

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025