Here is a snippet of the code:
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());
What happens is that isFile() returns true, isDirectory() returns false; and the delete and renameTo methods won't work. I have no idea why isDirectory() returns false since both file and file2 are created in the java project folder. Thanks.
You may have a slight misunderstanding of the file.isDirectory()
method. It returns true
if the file itself IS a directory, not if the file is IN a directory.
I think you may be misunderstanding what File.isDirectory()
does. From the 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
from: Java 7 File API
So indeed, it is testing to see if that file IS a directory, not whether or not it is inside of it :)
+1 upvote to quazzieclodo, he beat me to it! :D
You are not creating a file with:
new File
you are missing following code:
File file2 = new File(fileName + "2.txt");
file2.createNewFile();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.