我想要做的是无论文件是否存在,都创建一个文件。
我尝试使用 File.createNewFile()
,但这只会在文件不存在时创建文件。我应该使用 File.delete()
然后再使用 File.createNewFile()
吗?
还是有更清晰的方法吗?
FileWriter 还有一个构造函数,接受两个参数:文件名和一个布尔值。这个布尔值表示是追加还是覆盖现有文件。下面是两个 Java FileWriter 的示例:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
Writer
:BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");
如果文件abc.txt不存在,它会创建该文件。如果文件存在,它将覆盖原有内容。
您也可以使用FileWriter的另一个构造函数以追加模式打开文件:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");
上述构造函数的文档说明:
给定一个文件对象,构造一个FileWriter对象。如果第二个参数为true,则字节将被写入文件末尾而不是开头。
Files.write(file, bytes);
path
的类型是Path
。如果您正在使用File
类的实例,您可能需要将其转换为Path
类型,使用以下方法:Files.write(file.toPath(), bytes);
你可以在这里阅读更多关于这种方法的内容here:
换句话说,它打开文件以进行写入操作,如果文件不存在则创建文件
下面是一个测试,演示了该方法按预期工作:
@Test
void createsOrOverwrites(@TempDir final Path temp) throws IOException {
final Path text = temp.resolve("hello.txt");
Files.write(
text,
"Hello, world!".getBytes(StandardCharsets.UTF_8)
);
Assertions.assertTrue(Files.exists(text), "File should be created");
Assertions.assertEquals(
"Hello, world!",
Files.readAllLines(text).get(0),
"File should contain correct text"
);
Files.write(
text,
"I love StackOverflow!".getBytes(StandardCharsets.UTF_8)
);
Assertions.assertEquals(
"I love StackOverflow!",
Files.readAllLines(text).get(0),
"File should be overwritten"
);
}
假设路径有效且您对其具有写入权限,调用File#createNewFile
是安全的。如果已经存在该名称的文件,则它将只返回false:
File f = new File("myfile.txt");
if (f.createNewFile()) {
// If there wasn't a file there beforehand, there is one now.
} else {
// If there was, no harm, no foul
}
// And now you can use it.
File#createNewFile
的文档中明确说明,只有在该名称的文件尚不存在时才会创建一个新文件。因此,现有文件将保持不变,不会被替换。 - Basil Bourque