Copy the file to Windows
The class File
in the library dart:io
does not yet include methods copy()
and move()
.
To ferry me around until they arrive, I am trying to roll my own copy function. I am using below code on Windows, but it just creates 0kb file.
void copyFile(String input, String output) { var inFile = new File(input), outFile = new File(output); if (outFile.existsSync()) outFile.deleteSync(); // I realize this isn't required var inStream = null, outStream = null; try { inStream = inFile.openInputStream(); outStream = outFile.openOutputStream(FileMode.WRITE); inStream.pipe(outStream); } finally { if (outStream != null && !outStream.closed) outStream.close(); if (inStream != null && !inStream.closed) inStream.close(); } }
I have also tried replacing the string pipe
with print(inStream.read(100).toString());
and I am getting null
. The input file exists (otherwise I would get a FileIOException). Am I doing something wrong, or are the input streams broken under Windows?
I use:
- Dart editor version 0.3.1_r17463
- Dart SDK Version 0.3.1.2_r17463
Edit: Next steps (although this is not a "chunk"). Am I using streams incorrectly?
void copyFile(String input, String output) { var inFile = new File(input), outFile = new File(output); if (outFile.existsSync()) outFile.deleteSync(); // I realize this isn't required outFile.writeAsBytesSync(inFile.readAsBytesSync(), FileMode.WRITE); }
source to share
With your first piece of code, you end up with an empty file because it is pipe
not a synchronous method. Thus, a copy of the inputStream for outputStream is not triggered when the finally block is executed. By closing streams in that final block, you stop pipe
before it starts. Without this, the final block will execute correctly.
void copyFile(String input, String output) { final inStream = new File(input).openInputStream(); final outStream = new File(output).openOutputStream(FileMode.WRITE); inStream.pipe(outStream); }
Finally, you don't need to worry about closing streams, because it pipe
closes streams by default ever reached. See InputStream.pipe .
source to share