想写一个统计文件夹大小的程序。但是发现用File.length()统计的大小与系统统计的大小有出入,想知道原因,大家讨论一下。
代码:
import java.io.*;
import java.math.*;
/**
*
* @author Bernie
*/
public class TestFile
{
public static void main ( String args[])
{
File root = null;
if (args.length == 1)
{
root = new File(args[0]);
}
if (root.exists())
{
System.out.println("total byte: " + size( root ));
}
} public static BigDecimal size ( File root )
{
BigDecimal total = new BigDecimal( 0 );
if ( root.isDirectory() )
{
System.out.println("root is a directory");
File [] subs = root.listFiles();
for (int i=0;i<subs.length ;i++ )
{
total = total.add(size(subs[i]));
}
}
else if ( root.isFile() )
{
System.out.println("root is a file");
return new BigDecimal(root.length());
}
return total;
}
}
代码:
import java.io.*;
import java.math.*;
/**
*
* @author Bernie
*/
public class TestFile
{
public static void main ( String args[])
{
File root = null;
if (args.length == 1)
{
root = new File(args[0]);
}
if (root.exists())
{
System.out.println("total byte: " + size( root ));
}
} public static BigDecimal size ( File root )
{
BigDecimal total = new BigDecimal( 0 );
if ( root.isDirectory() )
{
System.out.println("root is a directory");
File [] subs = root.listFiles();
for (int i=0;i<subs.length ;i++ )
{
total = total.add(size(subs[i]));
}
}
else if ( root.isFile() )
{
System.out.println("root is a file");
return new BigDecimal(root.length());
}
return total;
}
}
就是右键属性里的统计。
奇怪的是换台机器试一下就好了
关于隐藏文件的问题倒是值得试一下看看
long totalSize=0;
File[] files = file.listFiles();
for(int i=1;i<=files.length;i++)
{
RandomAccessFile raf = new RandomAccessFile(files[i-1].getPath(),"rw");
totalSize += raf.length();
}
用这个可以得出D:\\receive文件夹总共有多少个字节