dart:io library
File, socket, HTTP, and other I/O support for non-web applications.
Important: Browser-based apps can't use this library.Only the following can import and use the dart:io library:
- Servers
- Command-line scripts
- Flutter mobile apps
- Flutter desktop apps
This library allows you to work with files, directories,sockets, processes, HTTP servers and clients, and more.Many operations related to input and output are asynchronousand are handled usingFutures orStreams, both of whichare defined in thedart:asynclibrary.
To use the dart:io library in your code:
import 'dart:io';For an introduction to I/O in Dart, see thedart:io librarytour.
File, Directory, and Link
An instance ofFile,Directory, orLink represents a file,directory, or link, respectively, in the native file system.
You can manipulate the file system through objects of these types.For example, you can rename a file or directory:
File myFile = File('myFile.txt');myFile.rename('yourFile.txt').then((_) => print('file renamed'));Many methods provided by theFile,Directory, andLink classesrun asynchronously and return aFuture.
FileSystemEntity
File,Directory, andLink all extendFileSystemEntity.In addition to being the superclass for these classes,FileSystemEntity has a number of static methods for working with paths.
To get information about a path,you can use theFileSystemEntity static methodssuch asFileSystemEntity.isDirectory,FileSystemEntity.isFile,andFileSystemEntity.exists.Because file system access involves I/O, these methodsare asynchronous and return aFuture.
FileSystemEntity.isDirectory(myPath).then((isDir) { if (isDir) { print('$myPath is a directory'); } else { print('$myPath is not a directory'); }});HttpServer and HttpClient
The classesHttpClient andHttpServer provide low-level HTTPfunctionality.
Instead of using these classes directly, consider using moredeveloper-friendly and composable APIs found in packages.
For HTTP clients, look atpackage:http.
For HTTP servers, look atWrite HTTP servers ondart.dev.
Process
TheProcess class provides a way to run a process onthe native machine.For example, the following code spawns a process that recursively liststhe files underweb.
Process.start('ls', ['-R', 'web']).then((process) { stdout.addStream(process.stdout); stderr.addStream(process.stderr); process.exitCode.then(print);});UsingProcess.start returns aFuture,which completes with aProcess object when the process has started.ThisProcess object allows you to interactwith the process while it is running.UsingProcess.run returns aFuture,which completes with aProcessResult object when the spawned process hasterminated. ThisProcessResult object collects the output and exit codefrom the process.
When usingProcess.start,you need to read all data coming on theProcess.stdout andProcess.stderrstreams, otherwise the system resources will not be freed.
WebSocket
TheWebSocket class provides support for the web socket protocol. Thisallows full-duplex communications between client and server applications.
A web socket server uses a normal HTTP server for accepting web socketconnections. The initial handshake is a HTTP request which is then upgraded to aweb socket connection.The server upgrades the request usingWebSocketTransformerand listens for the data on the returned web socket.For example, here's a mini server that listens for 'ws' dataon a WebSocket:
runZoned(() async { var server = await HttpServer.bind('127.0.0.1', 4040); server.listen((HttpRequest req) async { if (req.uri.path == '/ws') { var socket = await WebSocketTransformer.upgrade(req); socket.listen(handleMsg); } });}, onError: (e) => print("An error occurred."));The client connects to theWebSocket using theWebSocket.connect methodand a URI that uses the Web Socket protocol.The client can write to theWebSocket with theWebSocket.add method.For example,
var socket = await WebSocket.connect('ws://127.0.0.1:4040/ws');socket.add('Hello, World!');Check out thewebsocket_sampleapp, which usesWebSockets to communicate with a server.
Socket and ServerSocket
Clients and servers useSockets to communicate using the TCP protocol.UseServerSocket on the server side andSocket on the client.The server creates a listening socket using thebind() method andthen listens for incoming connections on the socket. For example:
ServerSocket.bind('127.0.0.1', 4041) .then((serverSocket) { serverSocket.listen((socket) { socket.transform(utf8.decoder).listen(print); }); });A client connects aSocket using theconnect() method,which returns aFuture.Usingwrite(),writeln(), orwriteAll() are the easiest ways tosend data over the socket.For example:
Socket.connect('127.0.0.1', 4041).then((socket) { socket.write('Hello, World!');});BesidesSocket andServerSocket, theRawSocket andRawServerSocket classes are available for lower-level accessto async socket IO.
Standard output, error, and input streams
This library provides the standard output, error, and inputstreams, namedstdout,stderr, andstdin, respectively.
Thestdout andstderr streams are bothIOSinks and have the same setof methods and properties.
To write a string tostdout:
stdout.writeln('Hello, World!');To write a list of objects tostderr:
stderr.writeAll([ 'That ', 'is ', 'an ', 'error.', '\n']);The standard input stream is a trueStream, so it inheritsproperties and methods from theStream class.
To read text synchronously from the command line(the program blocks waiting for user to type information):
String? inputText = stdin.readLineSync();Classes
- BytesBuilder
- Builds a list of bytes, allowing bytes and lists of bytes to be added at theend.
- CompressionOptions
- Options controlling compression in aWebSocket.
- ConnectionTask<
S> - A cancelable connection attempt.
- ContentType
- A MIME/IANA media type used as the value of theHttpHeaders.contentTypeHeader header.
- Cookie
- Representation of a cookie. For cookies received by the server as Cookieheader values onlyname andvalue properties will be set. When building acookie for the 'set-cookie' header in the server and when receiving cookiesin the client as 'set-cookie' headers all fields can be used.
- Datagram
- A data packet received by aRawDatagramSocket.
- Directory
- A reference to a directory (orfolder) on the file system.
- File
- A reference to a file on the file system.
- FileLock
- Type of lock when requesting a lock on a file.
- FileMode
- The modes in which aFile can be opened.
- FileStat
- The result of calling the POSIX
stat()function on a file system object. - FileSystemCreateEvent
- File system event for newly created file system objects.
- FileSystemDeleteEvent
- File system event for deletion of file system objects.
- FileSystemEntity
- The common superclass ofFile,Directory, andLink.
- FileSystemEntityType
- The type of an entity on the file system,such as a file, directory, or link.
- FileSystemEvent
- Base event class emitted byFileSystemEntity.watch.
- FileSystemModifyEvent
- File system event for modifications of file system objects.
- FileSystemMoveEvent
- File system event for moving of file system objects.
- GZipCodec
- TheGZipCodec encodes raw bytes to GZip compressed bytes and decodes GZipcompressed bytes to raw bytes.
- HeaderValue
- Representation of a header value in the form:
- HttpClient
- An HTTP client for communicating with an HTTP server.
- HttpClientBasicCredentials
- Represents credentials for basic authentication.
- HttpClientBearerCredentials
- Represents credentials for bearer token authentication.
- HttpClientCredentials
- Represents credentials for authentication inHttpClient.
- HttpClientDigestCredentials
- Represents credentials for digest authentication.
- HttpClientRequest
- HTTP request for a client connection.
- HttpClientResponse
- HTTP response for a client connection.
- HttpConnectionInfo
- Information about anHttpRequest,HttpResponse,HttpClientRequest, orHttpClientResponse connection.
- HttpConnectionsInfo
- Summary statistics about anHttpServers current socket connections.
- HttpDate
- Utility functions for working with dates with HTTP specific dateformats.
- HttpHeaders
- Headers for HTTP requests and responses.
- HttpOverrides
- This class facilitates overridingHttpClient with a mock implementation.It should be extended by another class in client code with overridesthat construct a mock implementation. The implementation in this base classdefaults to the actualHttpClient implementation. For example:
- HttpRequest
- A server-side objectthat contains the content of and information about an HTTP request.
- HttpResponse
- An HTTP response, which returns the headers and datafrom the server to the client in response to an HTTP request.
- HttpServer
- A server that delivers content, such as web pages, using the HTTP protocol.
- HttpSession
- TheHttpRequest.session of anHttpRequest.
- HttpStatus
- HTTP status codes. Exported in dart:io and dart:html.
- InternetAddress
- An internet address or a Unix domain address.
- InternetAddressType
- The type, or address family, of anInternetAddress.
- IOOverrides
- Facilities for overriding various APIs of
dart:iowith mockimplementations. - IOSink
- A combined byte and text output.
- Link
- References to filesystem links.
- NetworkInterface
- ANetworkInterface represents an active network interface on the currentsystem. It contains a list ofInternetAddresses that are bound to theinterface.
- Pipe
- An anonymous pipe that can be used to send data in a single direction i.e.data written towrite can be read usingread.
- Platform
- Information about the environment in which the current program is running.
- Process
- The means to execute a program.
- ProcessInfo
- Methods for retrieving information about the current process.
- ProcessResult
- The result of running a non-interactiveprocess started withProcess.run orProcess.runSync.
- ProcessSignal
- On Posix systems,ProcessSignal is used to send a specific signalto a child process, see
Process.kill. - ProcessStartMode
- Modes for running a new process.
- RandomAccessFile
- Random access to the data in a file.
- RawDatagramSocket
- An unbuffered interface to a UDP socket.
- RawSecureServerSocket
- A server socket providing a stream of low-levelRawSecureSockets.
- RawSecureSocket
RawSecureSocketprovides a secure (SSL or TLS) network connection.- RawServerSocket
- A listening socket.
- RawSocket
- A TCP connection.
- RawSocketEvent
- Events for theRawDatagramSocket,RawSecureSocket, andRawSocket.
- RawSocketOption
- TheRawSocketOption is used as a parameter toSocket.setRawOption andRawSocket.setRawOption to customize the behaviour of the underlyingsocket.
- RawSynchronousSocket
- A low-level class for communicating synchronously over a TCP socket.
- RawZLibFilter
- TheRawZLibFilter class provides a low-level interface to zlib.
- ReadPipe
- The "read" end of anPipe created byPipe.create.
- RedirectInfo
- Redirect information.
- ResourceHandle
- A wrapper around OS resource handle so it can be passed via Socketas part ofSocketMessage.
- SameSite
- Cookie cross-site availability configuration.
- SecureServerSocket
- A server socket, providing a stream of high-levelSockets.
- SecureSocket
- A TCP socket using TLS and SSL.
- SecurityContext
- The object containing the certificates to trust when makinga secure client connection, and the certificate chain andprivate key to serve from a secure server.
- ServerSocket
- A listening socket.
- Socket
- A TCP connection between two sockets.
- SocketControlMessage
- Control message part of theSocketMessage received by a call toRawSocket.readMessage.
- SocketDirection
- TheSocketDirection is used as a parameter toSocket.close andRawSocket.close to close a socket in the specified direction(s).
- SocketMessage
- A socket message received by aRawDatagramSocket.
- SocketOption
- An option for a socket which is configured usingSocket.setOption.
- Stdin
- The standard input stream of the process.
- StdioType
- The type of object a standard IO stream can be attached to.
- Stdout
- AnIOSink connected to either the standard out or error of the process.
- SystemEncoding
- The system encoding is the current code page on Windows and UTF-8 on Linuxand Mac.
- TlsProtocolVersion
- A Transport Layer Security (TLS) version.
- WebSocket
- A two-way HTTP communication object for client or server applications.
- WebSocketStatus
- WebSocket status codes used when closing a WebSocket connection.
- WebSocketTransformer
- TheWebSocketTransformer provides the ability to upgrade aHttpRequest to aWebSocket connection. It supports bothupgrading a singleHttpRequest and upgrading a stream ofHttpRequests.
- WritePipe
- The "write" end of anPipe created byPipe.create.
- X509Certificate
- X509Certificate represents an SSL certificate, with accessors toget the fields of the certificate.
- ZLibCodec
- TheZLibCodec encodes raw bytes to ZLib compressed bytes and decodes ZLibcompressed bytes to raw bytes.
- ZLibDecoder
- TheZLibDecoder is used byZLibCodec andGZipCodec to decompress data.
- ZLibEncoder
- TheZLibEncoder encoder is used byZLibCodec andGZipCodec to compressdata.
- ZLibOption
- Exposes ZLib options for input parameters.
Enums
- HttpClientResponseCompressionState
- Enum that specifies the compression state of the byte stream of anHttpClientResponse.
Constants
- gzip→ constGZipCodec
- An instance of the default implementation of theGZipCodec.
- systemEncoding→ constSystemEncoding
- The current system encoding.
- zlib→ constZLibCodec
- An instance of the default implementation of theZLibCodec.
Properties
- exitCode↔int
- Get the global exit code for the Dart VM.getter/setter pair
- pid→int
- Returns the PID of the current process.no setter
- stderr→Stdout
- The standard output stream of errors written by this program.no setter
- stdin→Stdin
- The standard input stream of data read by this program.no setter
- stdout→Stdout
- The standard output stream of data written by this program.no setter
Functions
Typedefs
- BadCertificateCallback=bool Function(X509Certificatecr,Stringhost,intport)
Exceptions / Errors
- CertificateException
- An exception that happens in the handshake phase of establishinga secure network connection, when looking up or verifying acertificate.
- FileSystemException
- Exception thrown when a file operation fails.
- HandshakeException
- An exception that happens in the handshake phase of establishinga secure network connection.
- HttpException
- IOException
- Base class for all IO related exceptions.
- OSError
- AnException holding information about an error from theoperating system.
- PathAccessException
- Exception thrown when a file operation fails because the necessary accessrights are not available.
- PathExistsException
- Exception thrown when a file operation fails because the target pathalready exists.
- PathNotFoundException
- Exception thrown when a file operation fails because a file ordirectory does not exist.
- ProcessException
- RedirectException
- SignalException
- SocketException
- Exception thrown when a socket operation fails.
- StdinException
- Exception thrown by some operations ofStdin
- StdoutException
- Exception thrown by some operations ofStdout
- TlsException
- A secure networking exception caused by a failure in theTLS/SSL protocol.
- WebSocketException