Skip to main content

Java For Python Programmers Edition 2

Section 8.6 Summary & Reading Questions

  1. To work with files in Java, you must import specific classes like java.io.File, java.io.FileWriter, and handle exceptions such as IOException.
  2. You can create a new file using File.createNewFile(), which returns true if the file is created and false if it already exists.
  3. Reading from files is done using a Scanner attached to a File, often with a loop using hasNextLine() and nextLine().
  4. To write to a file, use a FileWriter object and call methods like write() and close() to save and finish the output.
  5. You can delete a file using the delete() method on a File object, which returns true if successful.

Reading Questions Reading Questions

1.

Which import is needed to create and manipulate files in Java?
  • import java.util.File;
  • No, File is part of the java.io package, not java.util.
  • import java.io.File;
  • Correct! File is found in the java.io package.
  • import java.file.Input;
  • No, this is not a valid import for file operations.
  • import java.system.io.*;
  • No, there is no such package in Java.

2.

What does myFile.createNewFile() return if the file already exists?
  • It throws an exception.
  • No, it only throws an exception for access errors, not for existing files.
  • Correct! It returns false if the file already exists.
  • No, true is returned only when the file is successfully created.
  • No, null is not a valid return value for this method.

3.

Which method checks if a file has more lines to read using a Scanner?
  • nextLine()
  • No, nextLine() retrieves the next line, but does not check for availability.
  • hasMore()
  • No, this is not a method of Scanner.
  • hasNextLine()
  • Correct! This checks if there is another line available to read.
  • canReadLine()
  • No, this is not a standard method in the Scanner class.
You have attempted of activities on this page.