I created this simple example which is used to read Linux uptime:
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;
}
When I run the code I get this exception:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
Is there any other way to convert the result?
I believe you have to replace
long s = (long) Array.get(dic, 1);
with
long s = Long.valueOf((String) Array.get(dic, 1));
or even better:
long s = Long.valueOf(dic[1]);
The reason is that your array consists of String
object, and direct casting won't work.
The problem appears to be in the following line:
long s = (long) Array.get(dic, 1);
The get(Object array, int index) method of java.lang.reflect.Array returns an instance of Object, which cannot be directly cast to long.
You can access the element of the array simply by dic[1] instead of Array.get(dic, 1)
Replace with the following code:
long s = Long.parseLong(dic[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With