001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.fs; 019 020import java.io.File; 021import org.apache.hadoop.util.Shell; 022 023public class DUHelper { 024 025 private int folderCount=0; 026 private int fileCount=0; 027 private double usage = 0; 028 private long folderSize = -1; 029 030 private DUHelper() { 031 032 } 033 034 public static long getFolderUsage(String folder) { 035 return new DUHelper().calculateFolderSize(folder); 036 } 037 038 private long calculateFolderSize(String folder) { 039 if (folder == null) 040 throw new IllegalArgumentException("folder"); 041 File f = new File(folder); 042 return folderSize = getFileSize(f); 043 } 044 045 public String check(String folder) { 046 if (folder == null) 047 throw new IllegalArgumentException("folder"); 048 File f = new File(folder); 049 050 folderSize = getFileSize(f); 051 usage = 1.0*(f.getTotalSpace() - f.getFreeSpace())/ f.getTotalSpace(); 052 return String.format("used %d files %d disk in use %f", folderSize, fileCount, usage); 053 } 054 055 public long getFileCount() { 056 return fileCount; 057 } 058 059 public double getUsage() { 060 return usage; 061 } 062 063 private long getFileSize(File folder) { 064 065 folderCount++; 066 //Counting the total folders 067 long foldersize = 0; 068 if (folder.isFile()) 069 return folder.length(); 070 File[] filelist = folder.listFiles(); 071 if (filelist == null) { 072 return 0; 073 } 074 for (int i = 0; i < filelist.length; i++) { 075 if (filelist[i].isDirectory()) { 076 foldersize += getFileSize(filelist[i]); 077 } else { 078 fileCount++; //Counting the total files 079 foldersize += filelist[i].length(); 080 } 081 } 082 return foldersize; 083 } 084 085 public static void main(String[] args) { 086 if (Shell.WINDOWS) 087 System.out.println("Windows: "+ DUHelper.getFolderUsage(args[0])); 088 else 089 System.out.println("Other: " + DUHelper.getFolderUsage(args[0])); 090 } 091}