java中可以使用File类中的createNewFile()和createTempFile()方法,实现创建文件的功能。
1、createNewFile()方法定义为:public boolean createNewFile() throws IOException
使用createNewFile()方法时,如果指定的文件不存在并成功地创建文件,则返回true;如果指定的文件已经存在,则返回false。
2、createTempFile()方法主要用于创建临时文件,该方法重载了两次,具体定义如下:
public static File createTempFile(String prefix, String suffix) throws IOException
public static File createTempFile(String prefix, String suffix, File directory) throws IOException
参数prefix用于指定生成文件名的前缀字符串,必须至少是3个字符长。
参数suffix用于指定生成文件名的后缀字符串,可能是null,在这种情况下,将使用后缀“.tmp”。
参数directory用于指定将创建的文件所在的目录,如果使用默认临时文件目录,则该参数为null。
createTempFile(prefix, suffix)方法用于在默认临时文件目录中创建一个空文件,使用给定前缀、系统生成的随机数和后缀生成其名称。
示例代码如下:
File file = new File("D:\\test.txt");
//如果D:\\test.txt不存在,新建一个文件
if(file.exists()) {
file.createNewFile();
}
//在D盘下创建一个文件,文件名为tmp,随机数.log
try {
File.createTempFile("tmp", ".log", new File("D:\\"));
} catch(IOException e) {
e.printStackTrace;
}