技术控

    今日:69| 主题:49211
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Scala: Work With Files and Directories

[复制链接]
好了伤疤忘不了疼 发表于 2016-10-5 13:40:12
126 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
How often do you need to write or read files? This is a pretty common task in any more or less non-trivial project. Image upload process, CSV or XML parsing, XLS report generation etc. All these operations imply input or output processing. So I’m going to make an overview of the most powerful library for    working with files in Scala.  
  Here is a list of operations which I want to cover:
  
       
  • File creation and removal   
  • File writing and reading   
  • File comparison   
  • Zipping and unzipping  
  Of course, this list doesn’t limit the number of useful functions that you can perform with files and directories.
  The most suitable format for this article is tutorial plus example, so I’ll try to type more lines of code and less blah, blah, blah. If you want to discuss something, feel free to leave a comment.
  Looking a little ahead, I want to say that I will not write about native    scala.io.Source. Instead, I’ll show a powerful library called     better-files. The lib is written on top of Java NIO and has very transparent API.  
  Before we start, we need to add the library to a project. Here is a simple way to do this with SBT:
  1. libraryDependencies += "com.github.pathikrit" %% "better-files" % "2.16.0"
复制代码
Keep in mind that you need to use an appropriate version. At the moment of writing, 2.16.0 is the latest version.
  The next step is to add two imports:
  1. import better.files._
  2. import better.files.File._
复制代码
Finally, we can start manipulations with files.
  How to Create a File or Directory (Or Handle If It Doesn't Exist)

  1. val file1: File = "/Users/Alex/Downloads/file1.txt"
  2.   .toFile
  3.   .createIfNotExists()
复制代码
It’s so simple, isn’t it? After this code is executed,    file1.txtis created by the following path    /Users/Alex/Downloads/.  
  Look at the    createIfNotExists()method. You can pass parameters into it. For example, you want to create a directory.  
  1. val dir: File = "/Users/Alex/Downloads/dir"
  2.   .toFile
  3.   .createIfNotExists(true)
复制代码
Passing    trueinto the method, we force a    dirfolder creation by the path    /Users/Alex/Downloads/.  
  What about the creation of a folder with an extra path? Let’s assume that there are no directories in the    /Users/Alex/Downloads/.  
  1. val dir: File = "/Users/Alex/Downloads/extra/path/dir"
  2.   .toFile
  3.   .createIfNotExists(true, true)
复制代码
The code snippet above creates three folders:    extra,    path, and    dir.  
  The same approach can be applied to the file creation. If you want create a parent folder(-s) for the file, simply set    booleanvalue as the     createParentsparameter.  
  How to Write to a File

  The most popular question which you may find on StackOverflow. At least I think so. With help of better-files you can write to files easily!
  1. val html = (root/"Users/Alex/Downloads"/"test.html")
  2.   .createIfNotExists()
  3.   .append("<h1>")
  4.   .appendLines("", "Header", "</h1>")
复制代码
As you see, two options are allowed: write one line or write multiple lines. Also, you can write directly bytes in a file.
  Another useful input operation is an overwriting. In the context of the previous example, we can see how to write entirely new content to a file:
  1. html.overwrite("<p>Just one paragraph</p>")
复制代码
How to Read a File

  The most robust way to read all lines of text from a file is:
  1. val simpleFile = (root/"Users/Alex/Downloads"/"simple_file.txt")
  2.   .append("simple text")
  3. //simple text
  4. println(simpleFile.contentAsString)
复制代码
Alright! Getting an entire content as a string is pretty simple. But what if we want to traverse through a content line by line? It’s also possible:
  1. val simpleFile = (root/"Users/Alex/Downloads"/"simple_file.txt")
  2.   .overwrite("")
  3.   .appendLines("#1 line", "#2 line", "#3 line")
  4. simpleFile.lines.map(line => println(s"decor $line decor"))
复制代码
Voila!
  As I mentioned in the file writing section, you may want to work with bytes. Here is a small example of such an approach:
  1. val simpleFile = (root/"Users/Alex/Downloads"/"simple_file.txt")
  2.     .overwrite("I'm from simple_file.txt")
  3. val destinationFile = (root/"Users/Alex/Downloads"/"test.txt")
  4.     .write(simpleFile.byteArray)(OpenOptions.default)
  5. println(destinationFile.contentAsString)
复制代码
Delete Files and Directories

  Another group of popular questions is about the delete operation. Let’s consider the most trivial example, when we need to delete a file when it exists:
  1. import better.files._
  2. import better.files.File._0
复制代码
The same method can be applied to a process of directory deletion. Furthermore, it runs recursively and deletes all files and directories inside of a target folder.
  How to Compare Files and Folders

  It’s a pretty common scenario for developers. What does the better-files library suggest for solving this problem? Use    ==when you want to compare two files or directories by path. Use    ===when you want to check equality of two files or folders by content. The comparison of two folders' content has never been easier.  
  How to Zip and Unzip Files and Directories

  In order to zip file or directory, just use following construction:
  1. import better.files._
  2. import better.files.File._1
复制代码
When you need to unzip an archive, simply call the    unzipTomethod.  
  Summary

  I never thought that work with files may as so easy as it is with better-files. In this article, I showed the most popular operations, but with this library you can do much more. For example, you can copy the file or directory to some destination, work with file attributes (extension, size), set permissions, scan content. Now you understand why this library works with files like a boss!
友荐云推荐




上一篇:Introducing the Auth0 JWT Handbook
下一篇:exec will eat your brain
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表