|
| 1 | +// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import "dart:io"; |
| 6 | + |
| 7 | +const sampleText = "Sample text file."; |
| 8 | + |
| 9 | +main() async { |
| 10 | + var file = await createFile(); |
| 11 | + var uri = new Uri.file(file.path); |
| 12 | + |
| 13 | + var resource = new Resource(uri.toString()); |
| 14 | + |
| 15 | + if (resource.uri != uri) { |
| 16 | + throw "Incorrect URI: ${resource.uri}"; |
| 17 | + } |
| 18 | + |
| 19 | + var text = await resource.readAsString(); |
| 20 | + if (text != sampleText) { |
| 21 | + throw "Incorrect reading of text file: $text"; |
| 22 | + } |
| 23 | + |
| 24 | + var bytes = await resource.readAsBytes(); |
| 25 | + if (!compareBytes(bytes, sampleText.codeUnits)) { |
| 26 | + throw "Incorrect reading of bytes: $bytes"; |
| 27 | + } |
| 28 | + |
| 29 | + var streamBytes = []; |
| 30 | + await for (var byteSlice in resource.openRead()) { |
| 31 | + streamBytes.addAll(byteSlice); |
| 32 | + } |
| 33 | + if (!compareBytes(streamBytes, sampleText.codeUnits)) { |
| 34 | + throw "Incorrect reading of bytes: $bytes"; |
| 35 | + } |
| 36 | + |
| 37 | + await deleteFile(file); |
| 38 | +} |
| 39 | + |
| 40 | +/// Checks that [bytes] and [expectedBytes] have the same contents. |
| 41 | +bool compareBytes(bytes, expectedBytes) { |
| 42 | + if (bytes.length != expectedBytes.length) return false; |
| 43 | + for (int i = 0; i < expectedBytes.length; i++) { |
| 44 | + if (bytes[i] != expectedBytes[i]) return false; |
| 45 | + } |
| 46 | + return true; |
| 47 | +} |
| 48 | + |
| 49 | +createFile() async { |
| 50 | + var tempDir = await Directory.systemTemp.createTemp("sample"); |
| 51 | + var filePath = tempDir.path + Platform.pathSeparator + "sample.txt"; |
| 52 | + var file = new File(filePath); |
| 53 | + await file.create(); |
| 54 | + await file.writeAsString(sampleText); |
| 55 | + return file; |
| 56 | +} |
| 57 | + |
| 58 | +deleteFile(File file) async { |
| 59 | + // Removes the file and the temporary directory it's in. |
| 60 | + var parentDir = new Directory(file.path.substring(0, |
| 61 | + file.path.lastIndexOf(Platform.pathSeparator))); |
| 62 | + await parentDir.delete(recursive: true); |
| 63 | +} |
0 commit comments