Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use File.getFreeSpace() with any file to get the free space in Java?

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.

like image 696
Horcrux7 Avatar asked Oct 19 '13 12:10

Horcrux7


1 Answers

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.

like image 90
Srikanth Reddy Lingala Avatar answered Oct 14 '22 06:10

Srikanth Reddy Lingala