Java 文件位于目录中,但isDirectory()为文件返回false

Java 文件位于目录中,但isDirectory()为文件返回false,java,javascript,Java,Javascript,以下是代码片段: 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("delet

以下是代码片段:

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,如果文件位于目录中,则返回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
发件人:

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


+1投给quazzieclodo,他赢了我!:D

您创建的文件中没有:

new File
您缺少以下代码:

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

是文件和文件2目录吗?看起来不像。阅读javadoc。你误解了isDirectory的意思。你对isDirectory告诉你的东西有一个根本性的误解。这与文件是否在任何目录中无关,如果文件的路径是一个目录并注意到一个文件,则为真。C:\SomeFolder`是一个目录。C:\SomeFolder\SomeText.txt`不是目录。这与JavaScript有什么关系?