File i/o Flashcards

1
Q

How do you read a file line by line in Java?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you write to a file in Java?

A

Use PrintWriter or FileWriter.

PrintWriter writer = new PrintWriter(“output.txt”);
writer.println(“Hello, World!”);
writer.close();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you check if a file exists in Java?

A

se the exists() method from the File class.

File file = new File(“input.txt”);
if (file.exists()) {
System.out.println(“File exists”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you read words from a file into an array in Java?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you count the number of lines in a file?

A

Loop through the file with while (sc.hasNextLine())

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Write a snippet to write “Hello” to a file.

A

PrintWriter writer = new PrintWriter(“output.txt”);
writer.println(“Hello”);
writer.close();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you handle exceptions when working with files?

A

Use a try-catch block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What method checks if the file can be written to?

A

canWrite() method of the File class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you reverse the lines of a file?

A

Read lines into a list, reverse the list using Collections.reverse(), and write back to a file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between FileReader and FileWriter?

A

FileReader is for reading files; FileWriter is for writing files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you close a file after reading?

A

Call sc.close() for a Scanner object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly