Java Files and I/O

java

In Java, the java.io package provides classes and interfaces for reading and writing data to and from files.

Here are some common classes and methods for reading and writing text files:

FileReader: Reads characters from a file.
BufferedReader: Reads lines of text from a file.
FileWriter: Writes characters to a file.
BufferedWriter: Writes lines of text to a file.

Here is an example of how to read a text file in Java:

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

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}

This example reads the file line by line and prints each line to the console.

To write to a text file, you can use a similar approach:

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

try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
  writer.write("Hello, World!");
  writer.newLine();
  writer.write("This is a test.");
} catch (IOException e) {
  e.printStackTrace();
}

This example writes two lines of text to the file.

The java.nio package also provides classes for working with files, such as the Files class, which provides methods for reading, writing, and manipulating files and directories.