util.DirUsageUnixUtil.java Source code

Java tutorial

Introduction

Here is the source code for util.DirUsageUnixUtil.java

Source

/**
* Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org]
*
* This file is part of Redbasin OpenDocShare community project.
*
* Redbasin OpenDocShare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This contains some dirusage functions.
 *
 * @author Smitha Gudur (smitha@redbasin.com)
 * @version $Revision: 1.1 $
 */
public class DirUsageUnixUtil {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    /**
     * Uses du command on unix to get dir usage.
     *
     * @param dir 
     * @param file
     * @throws DirException
     * @return String
     */
    public String dirUsage(String dir, String file) throws DirException {
        try {
            Runtime runtime = Runtime.getRuntime();
            // It is important to break up the command into a String[] array
            // du -h --total -s
            Process proc = runtime.exec(new String[] { "/usr/bin/du", "-h", "--total", "-s", dir + file });
            InputStream stdin = null;
            int exitVal = proc.waitFor();
            if (exitVal == 0)
                stdin = proc.getInputStream();
            else
                stdin = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer output = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                //System.out.println("line = " + line);
                output.append(line);
            }
            return output.toString();
        } catch (Exception e) {
            throw new DirException("Could not get dir usage", e);
        }
    }
}