FTP samples
Example: Copy all files from an FTP server to local files
- list FTP server contents (1),
- just bother about file entries (2),
- for each file prepare for awaiting
Future
results ignoring the stream order (3), - run a new stream copying the file contents to a local file (4),
- combine the filename and the copying result (5),
- collect all filenames with results into a sequence (6)
- Scala
-
val ftpSettings = FtpSettings(InetAddress.getByName("localhost"), port) Ftp .ls("/", ftpSettings) // (1) .filter(ftpFile => ftpFile.isFile) // (2) .mapAsyncUnordered(parallelism = 5) { ftpFile => // (3) val localPath = targetDir.resolve("." + ftpFile.path) val dir = Files.createDirectories(localPath.getParent) val fetchFile: Future[IOResult] = Ftp .fromPath(ftpFile.path, ftpSettings) .runWith(FileIO.toPath(localPath)) // (4) fetchFile.map { ioResult => // (5) (ftpFile.path, ioResult) } } .runWith(Sink.seq) // (6)
- Scala Imports
-
import java.net.InetAddress import java.nio.file.{Files, Paths} import akka.actor.ActorSystem import akka.stream.alpakka.ftp.FtpSettings import akka.stream.alpakka.ftp.scaladsl.Ftp import akka.stream.scaladsl.{FileIO, Sink} import akka.stream.{ActorMaterializer, IOResult} import org.apache.mina.util.AvailablePortFinder import scala.collection.immutable import scala.concurrent.Future import scala.util.{Failure, Success} import scalasthlm.alpakka.playground.FtpServerEmbedded import scalasthlm.alpakka.playground.filesystem.FileSystemMock
Running the example code
This example is contained in a stand-alone runnable main, it can be run from sbt
like this:
- Scala
-
sbt > ftpSamples/run
The source code for this page can be found here.