Pull to refresh

JAVA класс для определения свободного места под *nix

Reading time3 min
Views730
Как-то, при написании биллинга, у меня возникла необходимость
определять оставшееся место на диске, для хранения бекапов.
Задачей было сделать rotate бекапов, на серверах, где хранились
детальные данные о траффике достаточно большой сети.
Поиски готовых решений успехом не увенчались.
Пришлось писать свой класс. Выкладываю сюда, ничего сложного, но вдруг кому пригодится.

Исходники

Хабр, правда, немного код калечит…

package com.unkur.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Only to use on *nix OS
 * Class represents info about mounted partitions
 * and free/used space on it.
 * It calls df system tool to get required data.
 * @author dmytro@unkur.com
 */
public class SpaceInfo {

    /**
     * Contains info about mounted partiotion.
     * @author dmytro@unkur.com
     */
    private class MountedItemInfo{

        public String mountedOn;
        public int available;
        public int used;
        public int size;
        public int capacity;

        public MountedItemInfo(String[] params){
            this.size = (new Integer(params[1])).intValue();
            this.used = (new Integer(params[2])).intValue();
            this.available = (new Integer(params[3])).intValue();
            this.capacity = (new Integer(params[4].substring(0,params[4].length()-1))).intValue();
            this.mountedOn = params[5];
        }

        public String toString(){
        	return "Mount Path:"+this.mountedOn+", Size:"+this.size+", Used:"+
            this.used+", Available:"+this.available+", Capacity:"+this.capacity+"%";
        }
    }

    private HashMap mountMap;

    /**
     * Converts(writes) InputStream to String
     * @param in
     * @return
     * @throws IOException
     */
    private static String inputStreamToStr(InputStream in) throws IOException{
        StringBuffer out = new StringBuffer();
        byte[] buf = new byte[4096];
        for (int readCount; (readCount = in.read(buf)) != -1;) {
        	out.append(new String(buf, 0, readCount));
        }
        in.close();
        return out.toString();
    }

    /**
     * Executes "df -a" command in unix console and updates info
     * about available space and drives capacity.	
     */
    public void updateSpaceInfo() throws IOException{
        this.mountMap = new HashMap();
        Runtime runtimeObj = Runtime.getRuntime();
        Process dfProc;
        dfProc = runtimeObj.exec("df -a");
        InputStream dfIS = dfProc.getInputStream();
        String consoleAnswer = inputStreamToStr(dfIS);
        String[] cAnswerRows = consoleAnswer.split("\n");
        for ( int iRow=1; iRow < cAnswerRows.length; iRow++ ){
            String[] driveParams = cAnswerRows[iRow].split(" +");
            if (driveParams.length==6){
                if (driveParams[4].substring(driveParams[4].length()-1).equals("%")){
                    MountedItemInfo itemInfo = new MountedItemInfo(driveParams);
                    this.mountMap.put(driveParams[5],itemInfo);
                }
            }
        }
    }

    /**
     * The constructor
     */
    public SpaceInfo() throws IOException{
        this.updateSpaceInfo();
    }

    public boolean checkIfVolumeExists(String volume){
        if (this.mountMap.containsKey(volume)){
            return true;
        }
        return false;
    }

    /**
     * @return FreeSpace/AllSpace*100;
     */
    public float getVolumeCapacity(String volume) throws Exception{
        if (!this.mountMap.containsKey(volume)){
            throw new Exception("Required volume does not exist.");
        }
        MountedItemInfo info = (MountedItemInfo)this.mountMap.get(volume);
        return info.capacity;
    }

    /**
     * @param volume
     * @return Free Space(kb) on partition
     */
    public long getVolumeFreeSpace(String volume) throws Exception{
        if (!this.mountMap.containsKey(volume)){
            throw new Exception("Required volume does not exist.");
        }
        MountedItemInfo info = (MountedItemInfo)this.mountMap.get(volume);
        return info.available;
    }

    /**
     * @param volume
     * @return Used Space(kb) on partition
     */
    public long getVolumeUsedSpace(String volume) throws Exception{
        if (!this.mountMap.containsKey(volume)){
            throw new Exception("Required volume does not exist.");
        }
        MountedItemInfo info = (MountedItemInfo)this.mountMap.get(volume);
        return info.used;
    }

    /**
     * @return Set of mounted partitions
     */
    public Set getVolumes(){
        return mountMap.keySet();
    }

    public String toString(){
        Collection volumes = this.mountMap.values();
        Iterator vIt = volumes.iterator();
        String result = "";
        while(vIt.hasNext()){
            MountedItemInfo volume = (MountedItemInfo)vIt.next();
            result+=volume.toString()+"\n";
        }
        return result;
    }
}


Пы.Сы. Можно было регулярки использовать, но задача быстрее и легче решалась без них.
Если кому надо версия с регулярками — обращайтесь.
Tags:
Hubs:
Total votes 9: ↑6 and ↓3+3
Comments14

Articles