我创建了这个简单的示例,用于读取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无法转换为java.lang.Long
是否有其他方法可以将结果转换?