Show List

File Operations

Java I/O (Input/Output) operations allow a program to read data from input sources and write data to output destinations. Java provides a comprehensive I/O package, java.io, that includes classes for reading from and writing to a variety of input and output sources.

One common I/O operation is reading from the console. For example:

import java.util.Scanner;

Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.println("Hello, " + name + "!");

In this example, the Scanner class is used to read a line of text from the console. The nextLine method is used to read the line and the input is stored in a String variable named name.

File handling in Java allows you to read from and write to files on disk. Java provides the java.io.File class for representing files and the java.io.FileReader and java.io.FileWriter classes for reading from and writing to files. For example:

import java.io.*;

try {
   File file = new File("example.txt");
   FileWriter writer = new FileWriter(file);
   writer.write("Hello, File!");
   writer.close();

   FileReader reader = new FileReader(file);
   int character;
   while ((character = reader.read()) != -1) {
      System.out.print((char) character);
   }
   reader.close();
} catch (IOException e) {
   System.out.println("An I/O exception has occurred: " + e.getMessage());
}

In this example, a file named example.txt is created using the FileWriter class. The string "Hello, File!" is written to the file. The FileReader class is then used to read the contents of the file and print them to the console.

File handling is an important aspect of Java programming and is used in many applications for reading and writing data to disk. The java.io package provides a comprehensive set of classes and methods for working with files and I/O operations in Java.


    Leave a Comment


  • captcha text