Illuminatiiiiii
10/20/2018 - 9:59 PM

Writing to Files

Episode 55 of the Java Tutorial: https://youtu.be/tJHV5kZiPR0

import java.io.*;

public class Main {

    public static void main(String[] args) {
        try{
            FileOutputStream fout = new FileOutputStream("booty.txt"); //The file we are outputting to
            FileInputStream fin = new FileInputStream("lyrics.txt"); //The old file that copy text from to our new file
            int input; //the variable we use to store byte characters and then use to output into the new file
            do{
                input = fin.read(); //Reads one character from the file and stores it into input as a byte number
                if(input == -1){ //End of file from -1
                    System.out.println("Done copying file.");
                }else{
                    fout.write(input); //Takes a byte value and outputs it into the file as a character
                }
            }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(); //Asks the user for some input
            if (yesOrNo.equalsIgnoreCase("yes")){ //If the user types yes
                do{ //a loop that reads your input from the console and writes to the file output stream
                    input = br.read();
                    fout.write(input);
                }while (input != 'x'); //runs as long as they dont type x
            }
            System.out.println("Program done running");
            fin.close(); //closes our streams because we are done
            fout.close();
        }catch (IOException e){
            System.out.println(e);
        }
    }
}