文件在目录中,但isDirectory()为文件返回false

File is in the directory but isDirectory() returning false for a file

本文关键字:文件 false 返回 isDirectory      更新时间:2023-10-29

以下是代码片段:

String fileName = "High_Scores";
File file = new File(fileName + ".txt");
if(file.isFile())
  System.out.println("its a file");
if(!file.isDirectory())
   System.out.println("Not in directory");
if(file.delete())
  System.out.println("deleted");
else
  System.out.println(file.getAbsolutePath());
File file2  = new File(fileName + "2.txt");
boolean success = file2.renameTo(file);
if(success == true)
  System.out.println("renamed");
else
  System.out.println(file2.getAbsolutePath());

结果是isFile()返回true,isDirectory()返回false;delete和renameTo方法将不起作用。我不知道为什么isDirectory()返回false,因为file和file2都是在java项目文件夹中创建的。谢谢

您可能对file.isDirectory()方法有一点误解。如果文件本身是一个目录,而不是文件在一个目录中,则返回true

我想您可能误解了File.isDirectory()的作用。来自java 7 API:

public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
Where it is required to distinguish an I/O exception from the case that the file is not a directory, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
Returns:
true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file

来自:Java 7文件API

因此,实际上,它正在测试该文件是否是一个目录,而不是它是否在其中:)

+1投赞成票,他打败了我!:D

您不是在用创建文件

new File

您缺少以下代码:

File file2  = new File(fileName + "2.txt");
file2.createNewFile();