I'm trying to run the following command through java to show the current wifi signal strenght :
cat /proc/net/wireless | awk 'END { print $4 }' | sed 's/\.$//'
In the terminal this command works fine.
The function I use to run the commands is like :
public static String[] executeNativeCommand(String[] commands, String friendlyErrorMessage, String... arguments) throws RuntimeException {
if (commands == null || commands.length == 0)
return new String[]{};
Process listSSIDProcess = null;
try {
String[] replacedCommands = new String[commands.length];
for (int t = 0; t < commands.length; t++) {
replacedCommands[t] = MessageFormat.format(commands[t], (Object[])arguments);
}
listSSIDProcess = Runtime.getRuntime().exec(replacedCommands);
ByteArrayOutputStream output = new ByteArrayOutputStream();
IOUtils.copy(listSSIDProcess.getInputStream(), output);
return new String(output.toString()).split("\r?\n");
} catch (IOException e) {
if (friendlyErrorMessage == null) {
logger.error("Error masked due to the friendly error message not being set", e);
return new String[]{};
}
throw new RuntimeException(friendlyErrorMessage, e);
} finally {
if (listSSIDProcess != null) {
listSSIDProcess.destroy();
}
}
}
I tried to call it with :
public String getCurrentWiFiStrength(){
String[] output = IOUtilities.executeNativeCommand(new String[]{"cat /proc/net/wireless | awk 'END { print $4 }' | sed 's/.$//'"}, null);
if (output.length > 0) {
logger.info("Wireless strength :" + output);
return output[0];
}
else {
return null;
}
}
This didn't work so after some stackoverflow research I added /bin/sh and -c like this :
public String getCurrentWiFiStrength(){
String[] output = IOUtilities.executeNativeCommand(new String[]{"/bin/sh", "-c", "cat /proc/net/wireless | awk 'END { print $4 }' | sed 's/.$//'"}, null);
if (output.length > 0) {
logger.info("Wireless strength :" + output);
return output[0];
}
else {
return null;
}
}
This didn't work either. So I tried to run through terminal /bin/sh -c cat /proc/net/wireless | awk 'END { print $4 }' | sed 's/\.$//'
Which just keeps hanging and doesn't return anything... So I'm not sure what is going on and how to fix this... Any suggestions? I use tinkerOS (a debian based distro)
thanks in advance!
EDIT :
So I found out why it didn't work in shell, it was my escaping... The correct syntax is :
/bin/bash -c "cat /proc/net/wireless | awk 'END {print \$4;}' | sed 's/.$//'"
So I tried :
public String getCurrentWiFiStrength(){
String[] output = IOUtilities.executeNativeCommand(new String[]{"/bin/sh", "-c", "\"cat /proc/net/wireless | awk 'END {print \\$4;}' | sed 's/.$//'\""}, null);
if (output.length > 0) {
return output[0];
}
else {
return null;
}
}
Without too much luck... Any suggestions?
exec
and use aProcessBuilder
to create the process. Also break aString arg
intoString[] args
to account for things like paths containing space characters.