gpt4 book ai didi

java.lang.ClassCastException : java. lang.String 无法转换为 java.lang.Long

转载 作者:行者123 更新时间:2023-12-02 19:32:00 34 4
gpt4 key购买 nike

我创建了这个简单的示例,用于读取 Linux 正常运行时间:

public String getMachineUptime() throws IOException {
String[] dic = readData().split(" ");

long s = (long) Array.get(dic, 1);
return calculateTime(s);
}

private String readData() throws IOException {
byte[] fileBytes;
File myFile = new File("/proc/uptime");
if (myFile.exists()) {
try {
fileBytes = Files.readAllBytes(myFile.toPath());
} catch (java.nio.file.AccessDeniedException e) {
return null;
}

if (fileBytes.length > 0) {
return new String(fileBytes);
}
}
return null;
}

private String calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds)
- TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds)
- TimeUnit.DAYS.toMinutes(day)
- TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds)
- TimeUnit.DAYS.toSeconds(day)
- TimeUnit.HOURS.toSeconds(hours)
- TimeUnit.MINUTES.toSeconds(minute);

return "Day " + day + " Hour " + hours + " Minute " + minute
+ " Seconds " + second;
}

当我运行代码时,我收到此异常:

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long

还有其他方法可以转换结果吗?

最佳答案

我相信你必须更换

long s = (long) Array.get(dic, 1);

long s = Long.valueOf((String) Array.get(dic, 1));

或者更好:

long s = Long.valueOf(dic[1]);

原因是您的数组由 String 对象组成,并且直接转换不起作用。

关于java.lang.ClassCastException : java. lang.String 无法转换为 java.lang.Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26338361/

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