Basic File Reading and Writing in Java


Java provides several ways to read and write to files. Here’s a simple example using FileWriter and Scanner for writing and reading text files.

Source Code

// Writing to a file
try (FileWriter writer = new FileWriter("filename.txt")) {
    writer.write("Hello, Java!");
} catch (IOException e) {
    e.printStackTrace();
}

// Reading from a file
try (Scanner scanner = new Scanner(new File("filename.txt"))) {
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(line);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Java’s I/O streams (FileInputStream, FileOutputStream) and readers/writers (FileReader, FileWriter) offer flexibility for handling file operations, including character and binary data.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments