如何以功能风格进行文件创建和操作? [英] How to do File creation and manipulation in functional style?

查看:36
本文介绍了如何以功能风格进行文件创建和操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个程序,在其中运行一组指令并在目录中创建一个文件.一旦文件被创建,当再次运行相同的代码块时,它不应该运行相同的指令集,因为它之前已经被执行过,这里文件被用作保护.

I need to write a program where I run a set of instructions and create a file in a directory. Once the file is created, when the same code block is run again, it should not run the same set of instructions since it has already been executed before, here the file is used as a guard.

var Directory: String = "Dir1"
var dir: File = new File("Directory");
dir.mkdir();

var FileName: String = Directory + File.separator + "samplefile" + ".log"
val FileObj: File = new File(FileName)

if(!FileObj.exists())
    // blahblah
else 
{
    // set of instructions to create the file
}

程序最初运行时,文件不会出现,所以它应该运行else中的指令集并创建文件,第一次运行后,第二次运行它应该退出,因为文件存在.

When the programs runs initially, the file won't be present, so it should run the set of instructions in else and also create the file, and after the first run, the second run it should exit since the file exists.

问题是我不明白new File,文件是什么时候创建的?我应该使用 file.CreateNewFile 吗?另外,如何使用 case 以函数式风格编写它?

The problem is that I do not understand new File, and when the file is created? Should I use file.CreateNewFile? Also, how to write this in functional style using case?

推荐答案

了解 java.io.File 不是文件系统上的物理文件,而是路径名的表示——根据 javadoc:文件的抽象表示和目录路径名".所以 new File(...) 与创建实际文件无关 - 您只是定义了一个路径名,它可能与现有文件相对应,也可能不对应.

It's important to understand that a java.io.File is not a physical file on the file system, but a representation of a pathname -- per the javadoc: "An abstract representation of file and directory pathnames". So new File(...) has nothing to do with creating an actual file - you are just defining a pathname, which may or may not correspond to an existing file.

要创建一个空文件,您可以使用:

To create an empty file, you can use:

val file = new File("filepath/filename")
file.createNewFile();

如果在 JRE 7 或更高版本上运行,您可以使用新的 java.nio.file API:

If running on JRE 7 or higher, you can use the new java.nio.file API:

val path = Paths.get("filepath/filename")
Files.createFile(path)

如果您对默认的 IO API 不满意,您可以考虑多种替代方案.我所知道的特定于 Scala 的有:

If you're not happy with the default IO APIs, you an consider a number of alternative. Scala-specific ones that I know of are:

或者您可以使用 Java 世界中的库,例如 Google GuavaApache Commons IO.

Or you can use libraries from the Java world, such as Google Guava or Apache Commons IO.

一开始我没有考虑的事情:我将创建文件"理解为创建一个空文件";但是如果你打算立即在文件中写一些东西,你通常不需要先创建一个空文件.

One thing I did not consider initially: I understood "creating a file" as "creating an empty file"; but if you intend to write something immediately in the file, you generally don't need to create an empty file first.

这篇关于如何以功能风格进行文件创建和操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆