228k views
4 votes
Have a look at the lines of code below. Over the next 3 questions, we will write code that opens a file

named MyName.txt, read the first line from the file MyName.txt and display it, and then close it.



What should line number 20 be? The aim is to open a file named MyName.txt. Enter the entire line 20 i.e. start with File file =..



20 File file = new ________;


21 Scanner inputFile = new Scanner(file);


22 if (inputFile.hasNext())


23 {


24 String str =__________;


25 System.out.println(str);


26 }


27 ___________;

1 Answer

1 vote

Answer:

20 File file = new File("MyName.txt");

21 Scanner inputFile = new Scanner(file);

22 if(inputFile.hasNext())

23 {

24 String str = inputFile.next();

25 System.out.println(str);

26 }

Step-by-step explanation:

We should put the file path (in string) in Line 20. When using File class, we need to input the file directory path as argument to create a file object. This file object will become the input to create a Scanner object (Line 21) and hasNext() method is used to check if there is any contents in next token (Line 22). If so, use next() method to get the first line of contents and assigned it to variable str (Line 24) and print it out (Line 25).

User Pankaj Pandey
by
4.0k points