Search code examples
dartstdoutstdin

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


How to get input from stdin (from text file ) and write to stdout (to text file ) in dart lang ?

just like this one in python

import sys
sys.stdin = open('inp.txt','r')
sys.stdout = open('out.txt','w')

Solution

  • I'm not sure why you are using stdin and stdout to read/write files. Could you explain a bit more?

    On your example, the contents of "imp.txt" are not written to the file "out.txt".

    You can indeed write all the stdout contents to a file instead of the console in python. I am not sure if you can do the same on DART.

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

    If you want to save all the output of a dart script to a file, you can still do it using the standard command line for it.

    dart dart_script.dart > out.txt

    To read the contents from one file and write to another you can use the 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);
      });
    }
    

    To make it more effective, and understand more of the structure you can treat them as streams

    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 the equivalent to python sys.stdout.

    Stdin is a Stream. And it's used to read input data from the command line. And File.openRead() returns a Stream as well.

    So to print the contents of a file to StdOut you can use

    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
    }