创建文件是一种非常常见的IO操作,在这一小节中我们将学习如何在java中创建文件的几个方法。

在java中创建文件有三种流行的方法,下面将一个一个地来学习。

方法一:使用File.createNewFile()方法

java.io.File类可用于在Java中创建新文件。当初始化File对象时,需要提供一个文件名,然后调用createNewFile()方法来在Java中创建新文件。

如果创建新文件成功,则文件createNewFile()方法返回true,如果文件已存在则返回false。当它无法创建文件时,此方法也会抛出java.io.IOException异常。创建的文件为空且零字节。

当通过传递文件名来创建File对象时,它可以是绝对路径,或者只能提供文件名,或者可以提供相对路径。

对于非绝对路径,File对象尝试查找项目根目录中的文件。如果从命令行运行程序,对于非绝对路径,File对象会尝试从当前目录中查找文件。

在创建文件路径时,应该使用System属性file.separator来使程序平台独立。

下面让我们来看看使用java程序创建一个新文件的不同场景。

import java.io.File;
import java.io.IOException;
public class CreateNewFile {
/**
* 该类显示了如何在Java中创建文件
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String fileSeparator = System.getProperty("file.separator");
// 带路径的绝对文件名
String absoluteFilePath = "temp" + fileSeparator + "temp2" + fileSeparator + "file.txt";
System.out.println(System.getProperty("user.dir"));
File file = new File(absoluteFilePath);
if (file.createNewFile()) {// 工程目录下要有一个目录:temp/temp2
System.out.println(absoluteFilePath + " File Created");
} else
System.out.println("File " + absoluteFilePath + " already exists");
// 只提供文件名称
file = new File("file.txt");
if (file.createNewFile()) {
System.out.println("file.txt File Created in Project root directory");
} else
System.out.println("File file.txt already exists in the project root directory");
// 相对路径
String relativePath = "tmp" + fileSeparator + "file.txt";
file = new File(relativePath);
if (file.createNewFile()) {
System.out.println(relativePath + " File Created in Project root directory");
} else
System.out.println("File " + relativePath + " already exists in the project root directory");
}
}
当第一次在Eclipse IDE执行上述程序时,会生成以下输出。
D:\worksp\eclipsej2ee\TestJava
temp\temp2\file.txt File Created
file.txt File Created in Project root directory
Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at CreateNewFile.main(CreateNewFile.java:37)

对于相对路径,它会抛出IOException异常,因为项目根文件夹中不存在tmp目录。所以很明显createNewFile()只是尝试创建文件,任何绝对或相对的目录都应该存在,否则抛出IOException异常。所以需要在项目根目录中创建tmp目录并再次执行程序,输出如下所示 -

D:\worksp\eclipsej2ee\TestJava
File temp\temp2\file.txt already exists
File file.txt already exists in the project root directory
tmp\file.txt File Created in Project root directory

方法二: 使用FileOutputStream.write(byte[] b)方法

如果要创建新文件并同时并写入一些数据,可以使用FileOutputStream方法。下面是一个简单的代码片段,用于演示它的用法。上面讨论的绝对路径和相对路径的规则也适用于这种情况。

String fileData = "Maxsu from Yiibai.com";
FileOutputStream fos = new FileOutputStream("readme.txt");
fos.write(fileData.getBytes());
fos.flush();
fos.close();

方法三: 使用Java NIO Files.write()方法

可以使用Java NIO Files类来创建一个新文件并将一些数据写入其中。这是一个很好的选择,因为它不必担心关闭IO资源。

String fileData = "Maxsu from Yiibai.com";

Files.write(Paths.get("readme.txt"), fileData.getBytes());

上面就是在java程序中常用用于创建新文件的全部内容。