File i/o Flashcards
How do you read a file line by line in Java?
Use a Scanner object with a File.
Scanner sc = new Scanner(new File(“input.txt”));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
How do you write to a file in Java?
Use PrintWriter or FileWriter.
PrintWriter writer = new PrintWriter(“output.txt”);
writer.println(“Hello, World!”);
writer.close();
How do you check if a file exists in Java?
se the exists() method from the File class.
File file = new File(“input.txt”);
if (file.exists()) {
System.out.println(“File exists”);
}
How do you read words from a file into an array in Java?
Use ArrayList to store words.
ArrayList<String> words = new ArrayList<>();
Scanner sc = new Scanner(new File("words.txt"));
while (sc.hasNextLine()) {
words.add(sc.nextLine());
}
sc.close();</String>
How do you count the number of lines in a file?
Loop through the file with while (sc.hasNextLine())
Write a snippet to write “Hello” to a file.
PrintWriter writer = new PrintWriter(“output.txt”);
writer.println(“Hello”);
writer.close();
How do you handle exceptions when working with files?
Use a try-catch block
What method checks if the file can be written to?
canWrite() method of the File class
How do you reverse the lines of a file?
Read lines into a list, reverse the list using Collections.reverse(), and write back to a file.
What is the difference between FileReader and FileWriter?
FileReader is for reading files; FileWriter is for writing files.
How do you close a file after reading?
Call sc.close() for a Scanner object.