Does scala provide asynchronous non-blocking IO when working with files?

I am using scala 2.10, and I am wondering if there is some kind of package with asynchronous IO when working with files?

I did a search on this topic, but basically found examples, as shown below.

val file = new File(canonicalFilename) val bw = new BufferedWriter(new FileWriter(file)) bw.write(text) bw.close() 

what is essentially a java.io package with blocking I / O operations - write, read, etc. I also found a scala-io project with this intention, but it seems that the project is dead in the last activity of 2012.

What is the best practice in this scenario? Is there any scala package or a general way to wrap java.io code for futures and observations?

My use case from actor Akki is to manipulate files in a local or remote file system. Blocking must be avoided. Or is there a better alternative?

Thnaks for clarifying this

+6
source share
2 answers

Scala does not offer an explicit API for asynchronous IO I / O, however a simple Java API is exactly what you need to use in these cases (actually it’s good, we can use all these beautiful APIs without any packaging!). You should study the java.nio.channels.AsynchronousFileChannel , which is available with JDK7 and uses the underlying systems for asynchronous calls for the IO file.

Akka IO , without providing an IO file in it, has a module developed by Dario Rexin that makes it very easy to use AsynchronousFileChannel with Akka IO. Take a look at this library to use it: https://github.com/drexin/akka-io-file

In the near future, Akka will provide File IO in its akka-streams module. It can be like an external library for a while, although we are still not quite sure where to put it, since this requires users to have a JDK of at least 7, while most of Akka currently supports JDK6. Having said that, an asynchronous streaming IO file with back pressure will soon be created :-)

+5
source

If you use a tale stream to support async, it has file functionality that is built on the asynchronous java.nio APIs, which is probably the approach I would recommend. If you use standard scala futures, maybe you can use akka-io ? which, I think, uses Netty as a backend. Or you can call NIO directly - it takes only a few lines to convert the API based on a callback to scalaz or scala flags.

+3
source

Source: https://habr.com/ru/post/980412/


All Articles