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

时间:2013-11-25 22:30:26

标签: 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("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项目文件夹中创建的。感谢。

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

我认为你可能会误解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 File API

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

+1 upvote到quazzieclodo,他打败了我! :d

答案 2 :(得分:0)

您没有使用以下内容创建文件:

new File

您缺少以下代码:

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