Apps Read from file then convert to int

jiafish

Lurker
Hello, I am having some difficulties developing my first app.
My problem is a bit too specific so I couldn't find if any1 else had the same problem.


After writing a number as a string into memory and reading the said string from memory, I cannot convert it back into a number.

For example, the string written in is 1234, when I retrieve it and write it onto the app, it still shows up as 1234.
When I convert this string to an int using Integer.parseint(), it gives me an error. Then I tried converting a String 123 thats just declared, it works perfectly.

I assume it is the retrieving part that messed up the string and made it unable to be turned into an int. Any1 has any idea on how to fix this? or how to store numbers in memory in other ways?

Thank you.




heres the part of the code that retrieves the string and convert it


FileInputStream fIn = null;
InputStreamReader isr = null;
String data = null;

try{

char[] inputBuffer = new char[1024];

fIn = openFileInput(FILENAME);
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);

isr.close();
fIn.close();
}
catch(IOException e){
e.printStackTrace(System.err);
}


// Test to see the data.
TextView widget37 = (TextView) findViewById(R.id.widget37);
widget37.setText(data);

String test1 = "123"; //test string
// Transform the string to int
int numTotal = Integer.parseInt(data); //this is where it crashes.
 
When you are converting from the input buffer to the string, is it putting empty spaces into the string. You might try -

data = new String(inputBuffer).trim();

Or, is it possible to directly read from the FileInputStream to the String, as in -

data = isr.read();

Also, you can wrap the FileInputStream and FileOutputStream into DataInputStream and DataOutputStream that provide readInt and writeInt methods. I hope this helps.
 

jiafish

Lurker
Thread starter
the String(inputBuffer).trim fixes it
thank you very much
i guess it adds something like "\n" at the end of string when read and thats why it messed up
 
Top