user2455050
user2455050

Reputation: 17

total Ram from /proc/meminfo

i am getting in kb but i want ram in mb how i can get it as i am getting" MemTotal: 855000kb" but i want 855mb how to get ram in Mb and how to get only number is don't want Memtotal and kb

public void getTotalMemory() {  
{
    String str1 = "/proc/meminfo";
    String str2;        
    String[] arrayOfString;
    long initial_memory = 0;
    try {
        FileReader localFileReader = new FileReader(str1);
        BufferedReader localBufferedReader = new BufferedReader(    localFileReader, 8192);
        str2 = localBufferedReader.readLine();//meminfo
        arrayOfString = str2.split("\\s+");
        for (String num : arrayOfString) {
            Log.i(str2, num + "\t");
        }
        //total Memory
        initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;   
        localBufferedReader.close();
    } 
    catch (IOException e) 
    {       
    }
}  

Upvotes: 1

Views: 2280

Answers (4)

nori
nori

Reputation: 188

To close a resource cleanly, replace the close() call inside the try with a call in a finally clause:

...
finally{
    try {
        if (localBufferedReader != null) {
            localBufferedReader.close();
        }
    } catch (IOException e) {}
}

Upvotes: 2

TWA
TWA

Reputation: 12826

There are 1024 KB in 1 MB, so you can divide KB by 1024, not 1000 to get MB. That is if it's truly reporting in KB (technically kibibytes, KiB). Most developers refer to a kilobyte (KB) as 1024 bytes, not 1000 bytes.

1KB = 2^10 bytes

1MB = 2^20 bytes

1GB = 2^30 bytes

Upvotes: 1

Ben O
Ben O

Reputation: 169

I have provided updated code that provides a println of current memory in mb, Goodluck!

public static void getTotalMemory() {
String str1 = "/proc/meminfo";
String str2;        
String[] arrayOfString;
long initial_memory = 0;
try {
    FileReader localFileReader = new FileReader(str1);
    BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
    str2 = localBufferedReader.readLine();//meminfo
    arrayOfString = str2.split("\\s+");

    for (String num : arrayOfString) {
        //System.out.println(num + "\t");
    }
    //total Memory
    initial_memory = Integer.valueOf(arrayOfString[1]).intValue();   
    initial_memory = initial_memory/1024;

    System.out.println(initial_memory);
    localBufferedReader.close();
} 
catch (IOException e) 
{       
}

}

Upvotes: 0

Onur Topal
Onur Topal

Reputation: 3061

you can use regex to get only numbers and then use the math

string result = Regex.Replace(input, @"[^\d]", "");

But I am not use if MemTotal always return in kb. if it is also possible to return others like mb also get the last two chars and do your calculation according to that.

sorry above code for c# :) come to dark side

String result = input.replaceAll("[^\\d]", "");

Upvotes: 1

Related Questions