Answer:
See explaination
Explanation:
import java.io.File;
import java.io.PrintWriter;
public class Question4 {
/*
* For this exercise you will be doing some basic operations to write to a
* file. You will be creating your very own Secrets of the Universe (TM)
*
* You can use the PrintWriter class to write to files (Chapter 11.4)
*
* Your code should perform the following actions:
*
* 1) Open/Create a file for writing at the following location:
* "files/question4/MySecretsOfTheUniverse.txt" If the file already exists
* you will want to overwrite its contents. 2) Add at least 3 of your own
* secrets of the universe to the file. Each secret should be on its own
* line. 3) Make sure to close your file so that the results are saved.
*
* Note: Your code should not throw any checked exceptions.Note: You will
* need to import some classes from the java.io package.
*/
public static void Question4() {
// creating a File object
File file = new File("files/question4/MySecretsOfTheUniverse.txt");
try {
// opening print writer to write to the file. the file will be
// created if not exist, but you have to ensure that the directory
// files/question4/ exists.
PrintWriter writer = new PrintWriter(file);
// writing three random statements to the file. I dont know anything
// about the secrets of universe you mentioned, so I'm just writing
// some random stuff that came into my mind. You can replace below
// lines with whatever you want to write.
writer.println("Humans are aliens from Mars, sent here to colonize Earth after they screwed up mars.");
writer.println("This universe and everything in it are probably brain cells of some huge cosmic organism.");
writer.println("There may be other forms of life co-exist here on our Earth that we can't see,"
+ " because they vibrate at a different frequency outside of all our measurements");
//closing file, saving changes
writer.close();
} catch (Exception e) {
//printing error if exception is occurred.
System.err.println(e);
}
}
public static void main(String[] args) {
Question4();
}
}