🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Files Read/Write

Reading and Writing Files in Java

Reading Files:

  1. Using BufferedReader (Older Approach):
  2. import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadFileExample {
        public static void main(String[] args) {
            try (BufferedReader reader = new BufferedReader(new FileReader("path/to/your/file.txt"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.out.println("An error occurred while reading the file.");
                e.printStackTrace();
            }
        }
    }

    In this example, the BufferedReader is used to read the file line by line.

  3. Using Files.readAllLines (Java 7 and later):
  4. import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.io.IOException;
    import java.util.List;
    
    public class ReadFileWithNIOExample {
        public static void main(String[] args) {
            try {
                Path path = Paths.get("path/to/your/file.txt");
                List<String> lines = Files.readAllLines(path);
    
                for (String line : lines) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.out.println("An error occurred while reading the file.");
                e.printStackTrace();
            }
        }
    }

    This example uses the Files.readAllLines method to read all lines of the file into a list of strings.

Writing Files:

  1. Using BufferedWriter (Older Approach):
  2. import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class WriteFileExample {
        public static void main(String[] args) {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("path/to/your/output.txt"))) {
                writer.write("Hello, World!");
                writer.newLine();
                writer.write("This is a new line.");
            } catch (IOException e) {
                System.out.println("An error occurred while writing to the file.");
                e.printStackTrace();
            }
        }
    }

    This example uses the BufferedWriter to write text to a file.

  3. Using Files.write (Java 7 and later):
  4. import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.io.IOException;
    import java.util.Arrays;
    
    public class WriteFileWithNIOExample {
        public static void main(String[] args) {
            try {
                Path path = Paths.get("path/to/your/output.txt");
                Files.write(path, Arrays.asList("Hello, World!", "This is a new line."));
            } catch (IOException e) {
                System.out.println("An error occurred while writing to the file.");
                e.printStackTrace();
            }
        }
    }

    The Files.write method is used to write lines of text to a file.

Note:

  • Always close resources (such as BufferedReader or BufferedWriter) using try-with-resources or explicitly in a finally block to ensure proper resource management.
  • Make sure to handle exceptions appropriately, especially when working with file I/O, as file operations may throw IOException.

Choose the approach that fits your requirements and the Java version you are using. The java.nio.file package provides a more modern and flexible API for file operations in Java 7 and later.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.