HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Java Files

File handling is an important part of any application.

In Java, the term "files" can refer to various concepts related to file handling, input/output operations, and file manipulation..

Java File Handling

Java file handling involves performing operations on files and directories, such as reading from or writing to files, creating or deleting files, and managing directories. The core packages for file handling in Java are java.io (traditional I/O) and java.nio.file (NIO, introduced in Java 7 for more advanced I/O operations). Here's an overview of some common file handling operations using both approaches:

Traditional I/O (java.io package):

Reading from a File:

Example
 import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFromFile {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
              

Writing to a File:

Example
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
            writer.write("Hello, World!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}            
The File class has many useful methods for creating and getting information about files. For example:

Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not/td>
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory