Java tutorial
//package com.java2s; /** * Copyright 2014 Zhenguo Jin * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.text.TextUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class Main { public static final long GB = 1073741824; public static final long MB = 1048576; public static final long KB = 1024; public static String getFileSize(File file) { FileInputStream fis = null; try { fis = new FileInputStream(file); int length = fis.available(); if (length >= GB) { return String.format("%.2f GB", length * 1.0 / GB); } else if (length >= MB) { return String.format("%.2f MB", length * 1.0 / MB); } else { return String.format("%.2f KB", length * 1.0 / KB); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return "0"; } public static long getFileSize(String path) { if (TextUtils.isEmpty(path)) { return -1; } File file = new File(path); return (file.exists() && file.isFile() ? file.length() : -1); } }