File handling
Examples
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
public class FileHandlingExamples {
public static void main(String[] args) {
// Example 1: Reading from a file
// Place the input.txt file in the same directory as your Java source file
File inputFile = new File("input.txt");
try {
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Example 2: Writing to a file
// The output.txt file will be created in the same directory as your Java source file
File outputFile = new File("output.txt");
try {
PrintWriter writer = new PrintWriter(outputFile);
writer.println("Hello, world!");
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Example 3: Copying a file
// Place the source.txt file in the same directory as your Java source file
File sourceFile = new File("source.txt");
// The destination.txt file will be created in the same directory as your Java source file
File destFile = new File("destination.txt");
try {
Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
FAQ (interview questions and answers)
-
How do you read from a file in Java?
Using a Scanner
Using a PrintWriter
Using a FileWriter
-
What is the purpose of PrintWriter in file handling?
To read from a file
To close a file
To write to a file
-
How can you copy a file in Java?
Using FileWriter
Using Scanner
Using Files.copy()
-
What is the purpose of the close() method in file handling?
To open a file
To close an open file
To write to a file
-
What happens if you attempt to read from a non-existent file?
An IOException is thrown
A FileNotFoundException is thrown
A NoSuchFileException is thrown
Your Total Score: 0 out of 5
Remember to just comment if you have any doubts or queries.

No comments:
Post a Comment
Note: Only a member of this blog may post a comment.