如何从dart中的txt文件获取输入和写入输出

How to get input and write output from txt files in dart

如何在 dart lang 中从标准输入(从文本文件)获取输入并写入标准输出(到文本文件)?

就像python

中的这个一样
import sys
sys.stdin = open('inp.txt','r')
sys.stdout = open('out.txt','w')

我不确定您为什么使用 stdinstdout 到 read/write 文件。你能再解释一下吗?

在您的示例中,"imp.txt" 的内容未写入文件 "out.txt"

您确实可以将所有标准输出内容写入文件而不是 python 中的控制台。我不确定您是否可以在 DART 上做同样的事情。

import sys
sys.stdout = open('out.txt','w')
print('test') # anything that goes to stdout will be written to the "out.txt"

如果您想将 dart 脚本的所有输出保存到一个文件中,您仍然可以使用标准命令行来完成。

dart dart_script.dart > out.txt

要从一个文件读取内容并写入另一个文件,您可以使用 class File from the module dart:io.

import 'dart:io';

void main() {
  new File('inp.txt').readAsString().then((String contents) {
    new File('out.txt').writeAsString(contents);
  });
}

为了使其更有效,并了解更多结构,您可以将它们视为流

import 'dart:io';

void main() {
  final inpFile = new File('inp.txt');
  Stream<List<int>> inputStream = inpFile.openRead();

  final outFile = new File('out.txt');
  IOSink outStream = outFile.openWrite();

  outStream.addStream(inputStream);
  outStream.close();
}

Stdin is the equivalent to python sys.stdin and Stdout 相当于 python sys.stdout.

Stdin 是一个 Stream。它用于从命令行读取输入数据。还有File.openRead()returns一个Stream

因此,要将文件内容打印到 StdOut,您可以使用

import 'dart:io';

void main() {
  final inpFile = new File('inp.txt');
  Stream<List<int>> inputStream = inpFile.openRead();

  stdout.addStream(inputStream); //print all contents of file to stdout
}

我不相信 Dart 的 dart:io 库允许您像 Python 那样覆盖 stdinstdout

您可以使用 Process.start 启动一个新进程,然后写入其 stdin 或从其 stdout 读取,但您不能更改 stdin/ stdout 当前进程。