简体   繁体   English

以流方式写入文件并在达到给定 memory 文件大小时停止

[英]Writing into a file in a streaming way and stop when we reach a given memory file size

Let's say I want to save a stream of MyItem into a file (in JSON for example).假设我想将MyItem的 stream 保存到文件中(例如在 JSON 中)。 I would like to stop when the file reach a certain size limit in bytes.当文件达到一定的字节大小限制时,我想停止。 I would like to do it in Haskell... streaming is not the issue for me it's more how to get the file size information after each item put into this file...我想在 Haskell 中执行此操作...流式传输对我来说不是问题,更重要的是如何在将每个项目放入此文件后获取文件大小信息...

I don't think pipes anything for this out of the box, but it's easy to write your own toHandleBounded .我不认为开箱即用为此提供任何pipes ,但编写自己的toHandleBounded很容易。

On each step you check the file size and if it's less than the limit you loop, writing another block to the file.在每个步骤中,您检查文件大小,如果它小于您循环的限制,则将另一个块写入文件。

toHandleBounded :: MonadIO m => Integer -> Handle -> Consumer' ByteString m ()
toHandleBounded limit hd = do
  current <- liftIO $ hTell hd
  when (current < limit) $ do
    x <- await
    liftIO $ hPut hd x
    toHandleBounded limit hd

main :: IO ()
main =
  withFile "/dev/urandom" ReadMode $ \hIn ->
  withFile "out.txt" WriteMode $ \hOut ->
    runEffect $ P.fromHandle hIn >-> toHandleBounded (1024 * 500 ) hOut

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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