createNewFile()函数是Java中File类的一部分。此函数创建新的空文件。如果抽象文件路径不存在并且创建了新文件,则该函数返回true。如果文件名已经存在,则返回false。
函数签名:
public boolean createNewFile()
用法:
boolean var = file.createNewFile();
参数:此方法不接受任何参数。
返回类型:该函数返回表示是否创建新文件的布尔数据类型。
异常:此方法引发以下异常:
IO异常:如果发生输入输出错误
安全异常 :如果对文件的写访问被拒绝
以下示例程序旨在说明createNewFile()函数的用法:
范例1:文件“F:\\program.txt”是F:目录中的现有文件。
// Java program to demonstrate
// createNewFile() method of File Class
import java.io.*;
public class solution {
public static void main(String args[])
{
try {
// Get the file
File f = new File("F:\\program.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
}
}
输出:
File created
范例2:文件“F:\\program1.txt”不存在
// Java program to demonstrate
// createNewFile() method of File Class
import java.io.*;
public class solution {
public static void main(String args[])
{
try {
// Get the file
File f = new File("F:\\program1.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
}
}
输出:
File already exists
注意:程序可能无法在在线IDE中运行。请使用离线IDE并设置文件的路径。