我想检查一个特定的文件是否已经存在于同一个文件夹中。 如果它不存在,则创建一个新文件并输入特定的内容。例如, 。如果filePath = test.txt和test.txt不存在。 创建一个新的文件名test.txt并将12345放在文件的第一行。检查文件是否已经存在于相同的路径
目前我的方法甚至不会运行这个if语句,尽管满足条件。 (test.txt的不存在)
PrintWriter output;
File file = new File(filePath);
if(!file.isFile()){
try {
output = new PrintWriter(new FileWriter(filePath));
} catch (IOException ex) {
throw new PersistenceException("Error!", ex);
}
output.print("12345");
output.flush();
output.close();
}
您可以使用[exists()](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists())可用于'File'对象。 –
如果它确实存在?如果它存在但没有12345呢? – EJP