Illuminatiiiiii
10/21/2018 - 2:09 AM

Automatically Closing File Streams

For Episode 56 of the Java Tutorial: https://youtu.be/-y7DWd08cX8

import java.io.*;

public class Main {

    public static void main(String[] args) {
        try(FileOutputStream fout = new FileOutputStream("booty.txt");FileInputStream fin = new FileInputStream("lyrics.txt")){ //Double auto-close usage. just separate by a semicolon
            int input; 
            do{
                input = fin.read(); 
                if(input == -1){ 
                    System.out.println("Done copying file.");
                }else{
                    fout.write(input); 
                }
            }while(input != -1);
            System.out.println("Would you like to add some more stuff to the new file? yes or no");
            InputStreamReader ir = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(ir);
            String yesOrNo = br.readLine(); 
            if (yesOrNo.equalsIgnoreCase("yes")){ 
                do{ 
                    input = br.read();
                    fout.write(input);
                }while (input != 'x'); 
            }
            System.out.println("Program done running");
        }catch (IOException e){
            System.out.println(e);
        }
    }
}
import java.io.*;

public class Main {

    public static void main(String[] args) {

        int input;
        try(FileInputStream fin = new FileInputStream("lyrics.txt")){ //Use the stream declaration in the try parameter
            do{
                input = fin.read();
                System.out.println(input);
            }while(input != -1);
        }catch (IOException e){
            System.out.println(e);
        }


    }
}