Boolean exists = new File("F:\testFile.txt").exists();
How can I modify where my File object's .isFile() or .exists() methods checks for said file?
-
03-07-2022 - |
题
I was stuck for a few hours because in my conditional loop, the .isFile or .exists methods always returned false.. even when the file DID exist.
I wondered if it could be the string that I had passed to my file on initialization was being overwritten somehow.. but that wasn't the case, as I suspected.
It turned out that the directory or path the .isFile and .exists() methods look into are
C:\Users\MyComputerName\workspace\NameOfMyJavaProject\
directory.
This is the default where all of my stuff is stored. And so it all then clicked, it made sense why my boolean variable always returned false and allowed the creation of the same named file.. because it would look into the directory I posted above, NOT where I had the files being created.. Because I have the files created in my F:\
drive.
What could I do so that I could have the .isFile() and .exists() methods look into my F:\
drive?
解决方案
其他提示
To me this does not make much sense, but I will take a go anyway.
The .exists
and .isFile
method do not refer to a single point all the time, it is the file that it has been set to.
File f = new File("C:\FileOne.txt");
if(f.exists())
System.out.println("FileOne Exists at " + f.getAbsolutePath());
I solved the problem. Makky helpd me out a lot.
When I created the File
object called checkFile
to only return a true
or false
via
boolean yesOrNo = checkFile.isFile();
I created it simply as File checkFile = new File():
the solution was to do the following
create the file varialbe as File checkFile = new File("F:\\");
basically when I created the checkFile object, it was defaulted to where all my java projects are, unlike my file, which was created at a specific place.
All I had to do was change how I created the File object, as well.
I Know my explenation is weird so if anyone, months or years down the road needs me to clarify this, just bump the thread, I'll make sure to talk to you one on one if needed.
Again, thanks to Makky and everyone else that chimed in.