Frage

I'm looking at some sample code for creating a File in Java:

File f = new File("test/.././file.txt");

I'm confused at how this works - how can you have "test" , and then those .. and . in between like that? If I run this code in an arbitrary directory in my machine, why does it work(i.e I don't have a folder called "test" ).

this is part of some code for Path-Testing in java(getAbsolutePath() and etc)

thanks

War es hilfreich?

Lösung 3

the .. denote a parent directory; . denote this directory.

Having this as valid is another good reason why you should use getCanonicalPath() vs getAbsolutePath()

For example: Lets say your file is under /folder1/folder2 directory

then

File f = new File("/folder1/folder2/folder3/../<your file>");
f.getCanonicalPath() ==> /folder1/folder2/<your file>
f.getAbsolutePath() ==> /folder1/folder2/folder3/../<your file>

Andere Tipps

The .. just means "up a directory level". The single . just means "current directory level". Why they are in your file path is beyond me. Your path seems to mean "go into the test folder, then go up a level (to the one you started in), stay in that level, then look for file.txt". You could do the same thing with just new File("file.txt").

File f = new File("test/.././file.txt");  //.. is used to go one hierarchy above in the directory structure and . is for current directory

suppose you have directory structure like ABC/test/file.txt and if you are inside test then your . is path upto test and .. is path upto ABC as .. represents parent directory and parent of "test" is "ABC"

Because the .. goes back up the directory hierarchy, so you'll be back to where you started (not in test). This is unnecessary as it's equivalent to:

File("test.txt")

And so should work regardless of which directory you run it in.

The ".." will go up one directory from the current directory. So, this code is basically the same as new File("./file.txt");

./ goes to the directory where your project is located ../ Goes back a folder lets say you have a resource directory

Res/graphics/sprites/image.png

If you do File file = new File("./graphics/sprites/); That will point to the sprites directory

Now if you want to go back a file dir File newFile = file + "../";

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top