Domanda

How can I get the free disk space for any file? For a normal file like:

C:\Users\MyName\AppData\Local\Temp\somefile.tmp

I receive ever the value 0. Only for the root (partition) file like:

c:

I receive a real value. How can I find the root (partition) of any file? The problem seems also that there can be links in the parent hierarchy. This means c: must not be the partition of the file.

And of course should this work platform independent.

È stato utile?

Soluzione

File.getFreeSpace() works if the file exists in the specified location. For example:

File file = new File("D:\\1\\1.txt");
System.out.println(file.getFreeSpace());

will print out the free space remaining on Drive D only if 1.txt exists in the directory 1 in drive D. If not, this returns a 0. Maybe you can create a temporary file in the directory to query the free space and delete once you have it.

Altri suggerimenti

java.nio is great in these stuffs.

Use something like this get free space in disk:

    Files.getFileStore(Paths.get("path to file").toRealPath()).getUsableSpace();

To get root, you can use something like this:

Paths.get("path to file").toRealPath().getRoot()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top