Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. File Handling

Reading and Writing Text File

Reading and writing text files in Java can be achieved using BufferedReader and BufferedWriter for efficient text operations, as well as Scanner for convenient input processing. Below are detailed explanations and examples for each method:

1. Reading Text Files Using BufferedReader:

javaCopy codeimport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadTextFileWithBufferedReader {
    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) {
            e.printStackTrace();
        }
    }
}

In this example, BufferedReader is used to read text data line by line from the "input.txt" file. The readLine() method reads a line of text. The try-with-resources statement ensures that each resource is closed at the end of the statement.

2. Writing Text Files Using BufferedWriter:

javaCopy codeimport java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteTextFileWithBufferedWriter {
    public static void main(String[] args) {
        String content = "Hello, Text File!";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            bw.write(content);
            System.out.println("Data written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, BufferedWriter is used to write text data to the "output.txt" file. The write(String) method writes a string to the output stream.

3. Reading Text Files Using Scanner:

javaCopy codeimport java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadTextFileWithScanner {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("input.txt"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, Scanner is used to read text data line by line from the "input.txt" file. The hasNextLine() method checks if there is another line in the file, and nextLine() method reads the next line.

4. Writing Text Files Using BufferedWriter and User Input (Scanner):

javaCopy codeimport java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class WriteTextFileWithScanner {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("Enter text (type 'exit' to stop):");
            String input;
            while (!(input = scanner.nextLine()).equals("exit")) {
                bw.write(input + "\n");
            }

            System.out.println("Data written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, Scanner is used to read user input from the console, and the input is written to the "output.txt" file using BufferedWriter. The program continues to take input until the user types "exit".

Explanation:

  • Using BufferedReader and BufferedWriter:

    • BufferedReader is used for efficient reading of text from a character-input stream, such as a file.

    • BufferedWriter is used for efficient writing of text to a character-output stream, such as a file.

  • Using Scanner:

    • Scanner is a versatile class that can be used to read user input from the console or text from a file.

Remember to handle exceptions properly to ensure your file operations are robust and can handle any potential issues that may arise during reading and writing.

PreviousReading and Writing Binary FileNextSerialization and Deserialization

Last updated 1 year ago