Create a new class in Java and name it File1. Compile and run the code below. Th
ID: 3692643 • Letter: C
Question
Create a new class in Java and name it File1. Compile and run the code below. The first time you run the program, it should print "File quotiatons.txt not found" because no file by the name quotations.txt has been created yet. Now create an input file by launching Notepad and typing some of your favorite quotations in a file. Use Notepad to save the input fiile as quotations.txt in the same folder as your Java assignment. This time it should print your favorite quotations.
//displays contents of the file quotations.txt on the screen
import java.util.*;
import java.io.*;
public class File1
{
Public static void main(String args[]) throws IOException
{
File inputFile = new File("quotations.txt");
if ( !inputFile.exists())
{
System.out.println("File quotations.txt no found.");
System.exit(0);
}
Scanner input = new Scanner(inputFile);
String liine; //to hold one full line from the file
while (input.hasNext()) //while there is more data
{
line = input.nextLine(); //advance to next line, returns all "skipped" data
System.out.println(line);
}
input.close();
}
}
Explanation / Answer
import java.util.*;
import java.io.*;
public class HelloWorld
{
public static void main(String args[]) throws IOException
{
File inputFile = new File("quotations.txt");
if ( !inputFile.exists())
{
System.out.println("File quotations.txt no found.");
System.exit(0);
}
Scanner input = new Scanner(inputFile);
String line; //to hold one full line from the file
while (input.hasNext()) //while there is more data
{
line = input.nextLine(); //advance to next line, returns all "skipped" data
System.out.println(line);
}
input.close();
}
}
The program is working as required.Not sure what else do you want.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.