Input/Output (I/O) in java

Input/Output (I/O) in java


Input/Output (I/O) is a mechanism in Java that allows developers to read and write data to and from files and other external sources. Here is an example of how to use I/O in Java:



import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class Main {

  public static void main(String[] args) {

    try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {

      String line;

      while ((line = br.readLine()) != null) {

        System.out.println(line);

      }

    } catch (IOException e) {

      System.out.println("Error reading file");

    }

  }

}

In this example, we import the BufferedReader and FileReader classes from the java.io package. We then create a new BufferedReader object that reads data from a file called input.txt. We use a while loop to read each line of the file and print it to the console. If there is an error reading the file, we catch the IOException and print an error message.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...