Java File Handling Flashcards
Which package contains the File class?
The java.io class
What is the syntax to import the file class?
import java.io.File; // Import the File class
What is the syntax for specifying a new file?
File myObj = new File(“filename.txt”); // Specify the filename
What are some of the most often used methods on the file class?
canRead() , canWrite(), createNewFile() , delete() , exists() , getName() , length() , mkdir()
What is the syntax to import an exception?
import java.io.IOException; // Import the IOException class to handle errors
What class needs to be imported to write to a file?
import java.io.FileWriter; // Import the FileWriter class
What is the syntax to make the file to be writable?
FileWriter myWriter = new FileWriter(“filename.txt”);
What is the method to write to a file?
write()
What is the syntax to write to a file?
FileWriter myWriter = new FileWriter(“filename.txt”);
myWriter.write(“Files in Java might be tricky, but it is fun enough!”);
myWriter.close();
What class is used to read contents of a text file?
Scanner class
What is the syntax to import the Scanner class?
import java.util.Scanner; // Import the Scanner class to read text files
What is the syntax to read a file?
File myObj = new File("filename.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); System.out.println(data); } myReader.close();
What are some of the methods and syntax to get more information about a file?
File myObj = new File("filename.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length());
What is the syntax to delete a file?
import java.io.File; // Import the File class
public class DeleteFile { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.delete()) { System.out.println("Deleted the file: " + myObj.getName()); } else { System.out.println("Failed to delete the file."); } } }
What is the syntax to delete a folder?
import java.io.File;
public class DeleteFolder { public static void main(String[] args) { File myObj = new File("C:\\Users\\MyName\\Test"); if (myObj.delete()) { System.out.println("Deleted the folder: " + myObj.getName()); } else { System.out.println("Failed to delete the folder."); } } }