如何将可用磁盘空间转换为GB并打印它

时间:2016-04-21 13:26:26

标签: java arraylist ssh cmd

使用ssh.addCmd("wmic logicaldisk get caption, FreeSpace");  我能够以位为单位获得Windows机器的可用磁盘空间

================Response =============================

Caption  FreeSpace    
C:       13845487616  
D:       91357184000  
E:       0 

================Response =============================

以上回复已保存到字符串“响应”并能够打印出来。

我需要代码帮助将位转换为MB或GB,并以下面的格式显示。

=================================================

Caption  FreeSpace    
C:       1.73 GB  
D:       11.41 GB  
E:       0 GB

=====================================================

// Displays results of Tomcat nodes
import sshtool.Ssh;
import javax.swing.*;
import java.util.*;
JTextArea textarea = out;

def serverUserList =
    [

        "Servername or IP",
    ];

final myLock = new Object[0];
int i = 0,j=0,k=0;
//String myArr [] = new String[50];
for(server in serverUserList){
    Ssh ssh = new Ssh(){
        @Override
        public void finished(String cmd, String response){
            synchronized(myLock){

                textarea.append(this.ip +"\n");
                textarea.append( response);
            }
        }
    };
    //Stagger SSH connections by delaying each thread.
    ssh.setThreadDelayTime(3000*i);
    ssh.setIp(server);
    ssh.setGatewayIp("GatewayIP or Name");
    //ssh.setSharingSingletonGateway(true);
    ssh.setUsername("Domain\\Username");
    ssh.setKey("Password");
    ssh.addCmd("wmic logicaldisk get caption, FreeSpace");

    ssh.start();
}

1 个答案:

答案 0 :(得分:2)

我写了一个简单的测试来将字节转换为千字节,兆字节或千兆字节。

以下是测试结果:

13845487616 -> 12.89 GB
91357184000 -> 85.08 GB
123 -> 0.12 KB
1234 -> 1.21 KB
123456789 -> 117.74 MB

这是代码:

package com.ggl.testing;

public class PrintBytes {

    public static void main(String[] args) {
        long bytes = 13845487616L;
        System.out.println(bytes + " -> " + convertBytes(bytes));
        bytes = 91357184000L;
        System.out.println(bytes + " -> " + convertBytes(bytes));
        bytes = 123L;
        System.out.println(bytes + " -> " + convertBytes(bytes));
        bytes = 1234L;
        System.out.println(bytes + " -> " + convertBytes(bytes));
        bytes = 123456789L;
        System.out.println(bytes + " -> " + convertBytes(bytes));
    }

    public static String convertBytes(long bytes) {
        long kbDivisor = 1024L;
        long mbDivisor = kbDivisor * kbDivisor;
        long gbDivisor = mbDivisor * kbDivisor;

        if (bytes <= mbDivisor) {
            double kb = (double) bytes / kbDivisor;
            return String.format("%.2f", kb) + " KB";
        } else if (bytes <= gbDivisor) {
            double mb = (double) bytes / mbDivisor;
            return String.format("%.2f", mb) + " MB";
        } else {
            double gb = (double) bytes / gbDivisor;
            return String.format("%.2f", gb) + " GB";
        }

    }

}