通常在fileName.length()得到的會是long型態的bytes值,

其值非常的長並且不易閱讀,

透過以下funtion可以將byte轉換從BYTE到TB都沒有問題,

 回傳值為string型態, 丟入參數為長整數,

public String readableFileSize(long size) {
            if(size <= 0) return "0";
            final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
            int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
            return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
        }

 以下為呼叫此function的範例, 可以藉此驗證或測試

        public void toGetfileInfomation()
        {
            String fileName, fileReadableSize;
            long fileSize;

            File savePath = new File(dirName.getSavePath);
            File[] allFiles = savePath.listFiles();
            for(File file: allFiles){
                if(file.exists() == true && file.isFile() == true)
                    {
                        fileName = file.getName().toString(); //取得檔案名稱並轉為字串
                        fileSize = file.length();             //取得檔案大小
                        fileReadableSize = readableFileSize(fileSize); //轉為可讀格式
                       
/*印出test.jpg 100KB*/ fileInfoText.setText(fileName+ " " + fileReadableSize); }else{ System.out.println("error"); } } }

 

arrow
arrow

    Will 發表在 痞客邦 留言(0) 人氣()