天天看點

java 擷取檔案大小

有兩種方式

方式一:使用file 的length()方法;

方式二:使用fileinputstream的available()方法;

執行個體:

java 擷取檔案大小

@test  

    public void test01() throws ioexception {  

        string filepath = "d:\\bin\\pushpoxy-0.0.1-snapshot.jar";  

        system.out.println("file has " + new file(filepath).length()+ " bytes");  

        fileinputstream fis = null;    

        fis = new fileinputstream(filepath);    

        system.out.println("file has " + fis.available() + " bytes");  

    }  

運作結果 :

file has 29061936 bytes

其實這兩個方法時有差別的;

file 的length()方法 是擷取檔案所占硬碟空間大小;

fileinputstream的available()方法是還有多少位元組可以讀取.

available()方法的說明如下:

returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. the next invocation might be the same thread or another thread. a single read or skip of this many bytes will not block, but may read or skip fewer bytes. 

我們把上面的程式稍微修改一下:

java 擷取檔案大小

        fis = new fileinputstream(filepath);  

        byte[]bytes=new byte[10];  

        fis.read(bytes);  

        fis.skip(-10);  

 執行結果如下:

file has 29061926 bytes

總結:擷取檔案大小時建議使用file 的length()方法