Saturday, May 31, 2025

[JAVA] READ FILE FROM RUN

file in Java involves using classes from the java.io and java.nio.file packages. Here's a breakdown of common approaches:
1. Using BufferedReader:
This is a common way to read a file line by line.
It's efficient for larger text files due to buffering.
You'll need to handle potential IOExceptions. 
Java

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

public class ReadFile {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt"; // Replace with your file path
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}
The try-with-resources statement ensures the reader is closed automatically. 
reader.readLine() reads a line, returning null at the end of the file.
2. Using Files.readAllLines() (Java 7+)
This method reads all lines from a file into a List<String>.
It's convenient for smaller files.
It also requires handling IOExceptions.
Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class ReadFile {
    public static void main(String[] args) {
        Path filePath = Paths.get("path/to/your/file.txt"); // Replace with your file path
        try {
            List<String> lines = Files.readAllLines(filePath);
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}
3. Using Scanner:
Scanner can be used to read from various input sources, including files.
It can read line by line or token by token.
Java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {
        File file = new File("path/to/your/file.txt"); // Replace with your file path
        try (Scanner scanner = new Scanner(file)) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}
The try-with-resources statement ensures the scanner is closed.
4. Reading Character by Character:
You can use FileReader to read character by character, this method is useful if you need to process the file at a character level.
Java

import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt"; // Replace with your file path
        try (FileReader reader = new FileReader(filePath)) {
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}
Important Considerations:
File Paths: Use correct file paths, relative or absolute.
Error Handling: Always handle potential IOExceptions using try-catch blocks.
Resource Management: Close resources (like readers and scanners) in a finally block or using try-with-resources to prevent resource leaks.
File Encoding: Be mindful of file encoding (e.g., UTF-8) when reading text files. You can specify the character set when creating a FileReader or BufferedReader.
Command Line Arguments: If the file path is provided as a command-line argument, access it through the args array.
Choose the method that best suits your specific needs and file size. BufferedReader and Files.readAllLines() are generally preferred for most cases.

No comments: