我想检查特定文件是否已存在于同一文件夹中。如果它不存在,则创建一个新文件并输入某些内容。例如。如果 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();
}
您可以通过创建 File 对象并使用exist方法来检查文件是否存在。与 C 语言相比,Java 中的 File 对象不同,当您创建 File 对象时,您不一定会创建物理文件。
File file = new File(pathString);
if (file.exists())
{
// File already exists
}
else
{
// You can create your new file
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句