gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:41:43 25 4
gpt4 key购买 nike

使用ssh.addCmd(“wmic逻辑磁盘获取标题,FreeSpace”); 我能够获取 Windows 机器的可用磁盘空间(以位为单位)

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

Caption FreeSpace
C: 13845487616
D: 91357184000
E: 0

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

以上响应已保存到字符串“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();
}

最佳答案

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

以下是测试结果:

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";
}

}

}

关于java - 如何将可用磁盘空间转换为 GB 并打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36771050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com