File Handling

 File Handling 


File handling is an important aspect of any programming language, and Java provides a rich set of APIs for working with files and directories. Here is an example of how to read and write to a file in Java:



import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;


public class Main {

  public static void main(String[] args) {

    try {

      // Create a new file

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


      // Write some text to the file

      FileWriter writer = new FileWriter(file);

      writer.write("Hello, world!");

      writer.close();


      // Read the text from the file

      Scanner scanner = new Scanner(file);

      String text = scanner.nextLine();

      scanner.close();


      System.out.println(text);

    } catch (FileNotFoundException e) {

      e.printStackTrace();

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

In this example, we create a File object that represents a file called "myfile.txt". We then create a FileWriter object and use it to write the string "Hello, world!" to the file. We close the FileWriter object to ensure that all of the data is written to the file.

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...