文档管理中心
此版本文档已归档不再维护,推荐您使用最新版本

File 示例

File 常规操作:创建、删除、读写、关闭

代码如下:

收起
自动换行
深色代码主题
复制
  1. import std.fs.*
  2. import std.io.SeekPosition
  3. main() {
  4. let filePath: Path = Path("./tempFile.txt")
  5. if (File.exists(filePath)) {
  6. File.delete(filePath)
  7. }
  8. /* 在当前目录以 只写模式 创建新文件 'tempFile.txt',写入三遍 "123456789\n" 并关闭文件 */
  9. var file: File = File(filePath, OpenOption.Create(false))
  10. if (File.exists(filePath)) {
  11. println("The file 'tempFile.txt' is created successfully in current directory.\n")
  12. }
  13. let bytes: Array<Byte> = b"123456789\n"
  14. for (_ in 0..3) {
  15. file.write(bytes)
  16. }
  17. file.close()
  18. /* 以 追加模式 打开文件 './tempFile.txt',写入 "abcdefghi\n" 并关闭文件 */
  19. file = File(filePath, OpenOption.Append)
  20. file.write(b"abcdefghi\n")
  21. file.close()
  22. /* 以 只读模式 打开文件 './tempFile.txt',按要求读出数据并关闭文件 */
  23. file = File(filePath, OpenOption.Open(true, false))
  24. let bytesBuf: Array<Byte> = Array<Byte>(10, item: 0)
  25. // 从文件头开始的第 10 个字节后开始读出 10 个字节的数据
  26. file.seek(SeekPosition.Begin(10))
  27. file.read(bytesBuf)
  28. println("Data of the 10th byte after the 10th byte: ${String.fromUtf8(bytesBuf)}")
  29. // 读出文件尾的 10 个字节的数据
  30. file.seek(SeekPosition.End(-10))
  31. file.read(bytesBuf)
  32. println("Data of the last 10 bytes: ${String.fromUtf8(bytesBuf)}")
  33. file.close()
  34. /* 以 截断模式 打开文件 './tempFile.txt',写入 "The file was truncated to an empty file!" 并关闭文件 */
  35. file = File(filePath, OpenOption.Truncate(true))
  36. file.write(b"The file was truncated to an empty file!")
  37. file.seek(SeekPosition.Begin(0))
  38. let allBytes: Array<Byte> = file.readToEnd()
  39. file.close()
  40. println("Data written newly: ${String.fromUtf8(allBytes)}")
  41. File.delete(filePath)
  42. return 0
  43. }

运行结果如下:

收起
自动换行
深色代码主题
复制
  1. The file 'tempFile.txt' is created successfully in current directory.
  2. Data of the 10th byte after the 10th byte: 123456789
  3. Data of the last 10 bytes: abcdefghi
  4. Data written newly: The file was truncated to an empty file!

File 的一些 static 函数演示

代码如下:

收起
自动换行
深色代码主题
复制
  1. import std.fs.*
  2. main() {
  3. let filePath: Path = Path("./tempFile.txt")
  4. if (File.exists(filePath)) {
  5. File.delete(filePath)
  6. }
  7. /* 以 只写模式 创建文件,并写入 "123456789\n" 并关闭文件 */
  8. var file: File = File.create(filePath)
  9. file.write(b"123456789\n")
  10. file.close()
  11. /* 以 追加模式 写入 "abcdefghi\n" 到文件 */
  12. File.writeTo(filePath, b"abcdefghi", openOption: OpenOption.Append)
  13. /* 直接读取文件中所有数据 */
  14. let allBytes: Array<Byte> = File.readFrom(filePath)
  15. println(String.fromUtf8(allBytes))
  16. File.delete(filePath)
  17. return 0
  18. }

运行结果如下:

收起
自动换行
深色代码主题
复制
  1. 123456789
  2. abcdefghi
搜索
请输入您想要搜索的关键词