문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top