Java File Class

ht‮spt‬://www.theitroad.com

In Java, the File class is a class that represents a file or directory on the file system. It provides methods for creating, deleting, and managing files and directories.

To use the File class, you first need to create an instance of the class and pass the file or directory path as a parameter to the constructor. For example, to create a File object for a file called "test.txt" in the current directory, you can write:

File file = new File("test.txt");

Once you have a File object, you can use its various methods to manipulate the file or directory. Some of the most commonly used methods are:

  • exists(): Returns true if the file or directory exists.
  • isFile(): Returns true if the File object represents a file.
  • isDirectory(): Returns true if the File object represents a directory.
  • getName(): Returns the name of the file or directory.
  • getParent(): Returns the parent directory of the file or directory.
  • list(): Returns an array of File objects that represent the files and directories in the directory.
  • createNewFile(): Creates a new empty file with the name specified in the File object.
  • delete(): Deletes the file or directory represented by the File object.
  • mkdir(): Creates a new directory with the name specified in the File object.
  • renameTo(File dest): Renames the file or directory represented by the File object to the name specified in the dest parameter.

Here is an example of using the File class to create a new file, write some text to it, and then read the text back:

File file = new File("test.txt");

try {
    file.createNewFile();
    FileWriter writer = new FileWriter(file);
    writer.write("Hello, world!");
    writer.close();

    FileReader reader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(reader);
    String line = bufferedReader.readLine();
    System.out.println(line);
    bufferedReader.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this example, we create a new File object for a file called "test.txt". We then use the createNewFile() method to create a new empty file with that name. We write the string "Hello, world!" to the file using a FileWriter, and then read the text back from the file using a FileReader and a BufferedReader. The System.out.println() statement outputs the text that was read from the file.