简体   繁体   中英

Save a stream to file in vibe.d

我想保存一个 vibe.d 流,例如 HTTPClientResponse.bodyReader( InterfaceProxy!InputStream类型),但也保存其他潜在的 vibe.d 流到一个文件中,我如何最好地以内存高效的方式做到这一点而不复制所有数据内存?

In general for downloading files using a HTTP client you can use the vibe.inet.urltransfer package which offers a download convenience function which performs a HTTP request, handles redirects and stores the final output to a file.

download(url, file);

However if you want to take a raw input stream (for example when not handling redirects) you can use vibe.core.file : openFile to open/create a file as file stream and then write to that.

To then write to the file stream you've got two options:

  1. Either you directly call file.write(otherStream)
  2. Otherwise you can use vibe.core.stream : pipe

Directly calling write on the FileStream object is what is being used inside the vibe.d urltransfer module and is also recommended for files as it will read directly from the stream into the write buffer instead of using an additional temporary buffer which pipe would use.

Sample:

// createTrunc creates a file if it doesn't exist and clears it if it does exist
// You might want to use readWrite or append instead.
auto fil = openFile(filename, FileMode.createTrunc);
scope(exit) fil.close();
fil.write(inputStream);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM