Last active
April 21, 2022 12:10
-
-
Save bilal-fazlani/f7b1171e32d4a726e83cf127c4c35c52 to your computer and use it in GitHub Desktop.
zio nio and streams file IO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TestApp extends zio.ZIOAppDefault { | |
override def run = { | |
val filePath = "main.csv" | |
val program = for { | |
// read a csv file | |
lines <- ZStream | |
.fromFileName(filePath, 1024) | |
.via(ZPipeline.utfDecode) | |
.via(ZPipeline.splitLines) | |
.runCollect | |
// filter data | |
filtered = lines.filter(_.contains("abc")) | |
// open new file | |
fileChannel <- AsynchronousFileChannel.open( | |
Path("main.filtered.csv"), | |
StandardOpenOption.WRITE, | |
StandardOpenOption.TRUNCATE_EXISTING | |
) | |
// truncate new file | |
_ <- fileChannel.truncate(0) | |
// write header | |
headerBytes = s"${lines(0)}\n".getBytes | |
_ <- fileChannel.writeChunk(Chunk.from(headerBytes), 0L) | |
// append data | |
sink = fileChannel.sink(headerBytes.length) | |
_ <- ZStream | |
.fromChunk(filtered) | |
.intersperse("\n") | |
.via(ZPipeline.utf8Encode) | |
.run(sink) | |
} yield () | |
program | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object TestApp extends zio.ZIOAppDefault { | |
override def run = { | |
val filePath = "main.csv" | |
val newFilePath = "main.filtered.csv" | |
val program = for { | |
// read a csv file | |
lines <- Files.readAllLines(Path(filePath), Charset.defaultCharset) | |
// filter data | |
filtered = lines.filter(_.contains("abc")) | |
headerBytes = s"${lines(0)}\n".getBytes | |
// write header | |
_ <- Files.writeBytes( | |
Path(newFilePath), | |
Chunk.from(headerBytes), | |
StandardOpenOption.WRITE, | |
StandardOpenOption.TRUNCATE_EXISTING | |
) | |
// write data | |
_ <- Files.writeLines( | |
Path(newFilePath), | |
filtered, | |
Charset.defaultCharset, | |
Set(StandardOpenOption.WRITE, StandardOpenOption.APPEND) | |
) | |
_ <- zio.Console.printLine("DONE") | |
} yield () | |
program | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment