Practice Questions: File Handling in Dart
- Write a program to create a new text file named
sample.txt. - Demonstrate how to write a string to
sample.txtand confirm the operation. - Create a program that reads the contents of
sample.txtand prints them to the console. - Modify the program to append a new line to
sample.txt. - Write a program to read all lines from
sample.txtand print each line individually. - Check if
sample.txtexists before attempting to read from it. - Create a directory named
files_directoryand storesample.txtinside it. - Write a program to delete
sample.txtfromfiles_directory. - Demonstrate how to list all files in
files_directory. - Write a program to rename
sample.txttorenamed_sample.txt. - Create a program that reads a file and counts the total number of lines.
- Write a program to read a file and count how many times a specific word appears.
- Create a program that handles exceptions when trying to read from a non-existent file gracefully.
- Write a program that copies
sample.txtto a new file namedcopy_sample.txt. - Demonstrate how to delete the entire
files_directoryalong with its contents.
Solutions with Code Explanation
1. Write a program to create a new text file named sample.txt.
import 'dart:io';
void main() async {
File file = File('sample.txt');
try {
await file.create();
print('File created successfully.');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code creates a new file called sample.txt. The create() method is called on the File object, and if successful, it prints a confirmation message.
2. Demonstrate how to write a string to sample.txt and confirm the operation.
import 'dart:io';
void main() async {
File file = File('sample.txt');
try {
await file.writeAsString('Hello, Dart!');
print('Data written to file successfully.');
} catch (e) {
print('Error: $e');
}
}
Explanation: The writeAsString() method writes "Hello, Dart!" to sample.txt. If the write operation is successful, it prints a confirmation message.
3. Create a program that reads the contents of sample.txt and prints them to the console.
import 'dart:io';
void main() async {
File file = File('sample.txt');
try {
String contents = await file.readAsString();
print('File Contents:\n$contents');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code reads the entire content of sample.txt using readAsString() and prints it to the console.
4. Modify the program to append a new line to sample.txt.
import 'dart:io';
void main() async {
File file = File('sample.txt');
try {
await file.writeAsString('\nThis is an appended line.', mode: FileMode.append);
print('Data appended to file successfully.');
} catch (e) {
print('Error: $e');
}
}
Explanation: The writeAsString() method is used with FileMode.append to add a new line to the existing content of sample.txt.
5. Write a program to read all lines from sample.txt and print each line individually.
import 'dart:io';
void main() async {
File file = File('sample.txt');
try {
List<String> lines = await file.readAsLines();
print('File Lines:');
for (var line in lines) {
print(line);
}
} catch (e) {
print('Error: $e');
}
}
Explanation: This code reads the lines of sample.txt into a list and prints each line individually using a for loop.
6. Check if sample.txt exists before attempting to read from it.
import 'dart:io';
void main() async {
File file = File('sample.txt');
if (await file.exists()) {
String contents = await file.readAsString();
print('File Contents:\n$contents');
} else {
print('File does not exist.');
}
}
Explanation: Before reading the file, the program checks if it exists using exists(). If the file exists, it reads and prints the contents; otherwise, it informs the user.
7. Create a directory named files_directory and store sample.txt inside it.
import 'dart:io';
void main() async {
Directory directory = Directory('files_directory');
try {
await directory.create();
File file = File('${directory.path}/sample.txt');
await file.writeAsString('Hello from inside the directory.');
print('File created inside the directory successfully.');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code creates a directory called files_directory and then creates sample.txt inside that directory, writing a message to it.
8. Write a program to delete sample.txt from files_directory.
import 'dart:io';
void main() async {
File file = File('files_directory/sample.txt');
try {
await file.delete();
print('File deleted successfully.');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code deletes sample.txt from the files_directory using the delete() method.
9. Demonstrate how to list all files in files_directory.
import 'dart:io';
void main() async {
Directory directory = Directory('files_directory');
try {
await for (var entity in directory.list()) {
print(entity.path);
}
} catch (e) {
print('Error: $e');
}
}
Explanation: This code lists all files and directories in files_directory using the list() method and prints their paths.
10. Write a program to rename sample.txt to renamed_sample.txt.
import 'dart:io';
void main() async {
File file = File('files_directory/sample.txt');
try {
File renamedFile = await file.rename('files_directory/renamed_sample.txt');
print('File renamed to: ${renamedFile.path}');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code renames sample.txt to renamed_sample.txt using the rename() method and prints the new path.
11. Create a program that reads a file and counts the total number of lines.
import 'dart:io';
void main() async {
File file = File('sample.txt');
try {
List<String> lines = await file.readAsLines();
print('Total number of lines: ${lines.length}');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code reads all lines from sample.txt and prints the total count using the length of the list.
12. Write a program to read a file and count how many times a specific word appears.
import 'dart:io';
void main() async {
File file = File('sample.txt');
String targetWord = 'Dart';
try {
String contents = await file.readAsString();
int count = RegExp(r'\b$targetWord\b', caseSensitive: false).allMatches(contents).length;
print('The word "$targetWord" appears $count times.');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code counts occurrences of a specific word (case insensitive) in the file using a regular expression and prints the count.
13. Create a program that handles exceptions when trying to read from a non-existent file gracefully.
import 'dart:io';
void main() async {
File file = File('non_existent_file.txt');
try {
String contents = await file.readAsString();
print('File Contents:\n$contents');
} catch (e) {
print('Error: File not found.');
}
}
Explanation: This code attempts to read from a non-existent file and catches the exception, providing a user-friendly error message.
14. Write a program that copies sample.txt to a new file named copy_sample.txt.
import 'dart:io';
void main() async {
File sourceFile = File('sample.txt');
try {
File copyFile = await sourceFile.copy('copy_sample.txt');
print('File copied to: ${copyFile.path}');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code copies sample.txt to copy_sample.txt using the copy() method and prints the new file's path.
15. Demonstrate how to delete the entire files_directory along with its contents.
import 'dart:io';
void main() async {
Directory directory = Directory('files_directory');
try {
await directory.delete(recursive: true);
print('Directory and its contents deleted successfully.');
} catch (e) {
print('Error: $e');
}
}
Explanation: This code deletes files_directory and all its contents using delete(recursive: true), ensuring that everything inside is removed.