Reading and Writing Files II

The example below uses a try-with-resources statement. This was added to JDK 7. When implemented this way, you don’t have to explicitly close the streams – Java will do it for you when they are garbage collected.

import java.io.FileInputStream;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class FileIO {
    public static void main(String[] args) {

        try (Scanner sc = new Scanner(new FileInputStream("in.txt"));
            PrintWriter pw = new PrintWriter(new FileOutputStream("out.txt"))) 
        {

            String token;
            while (sc.hasNext()){
                token = sc.next();
                pw.println(token);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.toString());
            return;
        } 
    }
}

© 2017 – 2020, Eric. All rights reserved.