Dart Core Libraries 'dart:io'

Dart Core Libraries 'dart:io'

The dart:io library in Dart provides powerful tools for performing input and output operations, such as reading and writing files, interacting with the filesystem, handling network connections, and more.

It is particularly useful for building server-side applications and command-line tools in Dart.

Key Features of dart:io

1. File and Directory Operations

The dart:io library allows you to work with files and directories on the local filesystem, enabling tasks such as reading from or writing to files, checking file existence, creating directories, and listing directory contents.

Example - Reading from a File:

import 'dart:io';

void main() {
  File file = File('example.txt');
  if (file.existsSync()) {
    String contents = file.readAsStringSync();
    print('File contents: $contents');
  } else {
    print('File not found!');
  }
}

2. Networking and HTTP Requests

With dart:io, you can make HTTP requests, create servers, and handle network connections. This is essential for building web servers or performing network operations in Dart applications.

Example - Making an HTTP GET Request:

import 'dart:io';

void main() async {
  var httpClient = HttpClient();
  var request = await httpClient.getUrl(Uri.parse('https://example.com'));
  var response = await request.close();
  var responseBody = await response.transform(Utf8Decoder()).join();
  print('Response body: $responseBody');
}

3. Console Input and Output

The dart:io library provides utilities for interacting with the console, allowing you to read user input and display output in command-line applications.

Example - Reading User Input:

import 'dart:io';

void main() {
  stdout.write('Enter your name: ');
  String name = stdin.readLineSync();
  print('Hello, $name!');
}