My application reads the output of a command line programs which is always a 0-3 digit number. The data starts as a stringBuffer, is sent .toString and the third step is to convert it to an integer for comparison. The final step using Integer.parseInt raises a java.lang.NumberFormatException. For example, if the output of the command line program is "0", this is the exception.
08-08 18:31:30.167: ERROR/AndroidRuntime(26484): FATAL EXCEPTION: main
08-08 18:31:30.167: ERROR/AndroidRuntime(26484): java.lang.NumberFormatException: unable to parse '0
08-08 18:31:30.167: ERROR/AndroidRuntime(26484): ' as integer
08-08 18:31:30.167: ERROR/AndroidRuntime(26484): at java.lang.Integer.parse(Integer.java:433)
Notice the linebreak around '0'. I know conversion can be tricky and I've checked the charset and explicitly set it to UTF-8. Also I've tried to check for '\n' or other non numeric characters via this code before the conversion:
System.out.println(score);
for(char c: score.toCharArray()){
System.out.println(c);
}
This code may not sufficiently reveal the fault. However, if the program is left to run without the integer conversion, each single numeral number is printed as itself, and each multi-digit number is printed with a digit on each line without any extraneous characters.
I'm fairly certain that I'm trying to convert the pertinent data in addition to some extra invisible characters.
For Reference: The code of the subprocess call:
try{
Process subProc = Runtime.getRuntime().exec("data/data/com.app/bin/prog /sdcard/file");
BufferedReader reader = new BufferedReader(
new InputStreamReader(subProc.getInputStream(), Charset.defaultCharset()), 10);
int read;
char[] buffer = new char[10];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
subProc.waitFor();
score = output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(score);
for(char c: score.toCharArray()){
System.out.println(c);
}
return score;
And for kicks, the ParseInt function that raises the exception:
int score = Integer.parseInt(NativeClass.getScore(file));
Thanks in advance.
static int Character.digit(char ch, int radix)
method. Everything that is out of the range of numerical representation of 0-9 is your "bad" character.String.replaceAll("[^0-9]+", "")
will remove everything non-digit from your input, including \n
symbols.