Text file not writing and storing data properly
I am having some problems with creating and editing text files. The file never seems to store the data.
- I need to create a text file, if one is not available.
- If there is data in the file, read that data and make it available.
- The data stored is a
String
comprising of three integer values, separated by a,
Eg:String finalWrite = "3,5,1"
- So this string needs to be split up, and converted into integers to allow for addition of new counters.
- Those new counters need to be written into the text file stored on the device
There are no errors occurring, and no force closures.
I was only able to figure out that the values are not being stored properly, using Logcat.
I have reviewed documentation on the Android development site. If anyone can help or point me in the right direction, it would be much appreciated!
The write method that I am using:
public void WriteItIn() throws IOException
{
FileOutputStream fOut = openFileOutput("stats.txt", Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
ReadItIn(); //calls the read method, to get the values from the file
int tmp1 = 0 + countertmp + counter;
int tmp2 = 0 + counterpostmp + counterpos;
int tmp3 = 0 + counternegtmp + counterneg;
finalwrite = "" + tmp1 + "," + tmp2 + "," + tmp3;
osw.write(finalwrite);
osw.flush();
osw.close();
}
The Read method:
public void ReadItIn() throws IOException
{
FileInputStream fIn = openFileInput("stats.txt");
InputStreamReader isr = new InputStreamReader(fIn);
开发者_开发知识库 char[] inputBuffer = new char[fIn.available()];
isr.read(inputBuffer);
stringFromFile = new String(inputBuffer);
String [] tmp = stringFromFile.split("\\,");
if(tmp.length > 0)
{
Log.d("READ", " NOT NULL");
for(int i = 0;i<tmp.length ; i++)
{
String temper = tmp[i];
if(temper == null || temper == "")
{
Log.d("NULL", "NULLIFIED");
}
else
try
{
int x = Integer.parseInt(temper, 10);
if(i == 0){counter = x;}
else if(i == 1){counterpos = x;}
else if(i == 2){counterneg = x;}
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
}
}
else
Log.d("READ", "NULL");
}
The main problem is that as soon as you invoke openFileOutput
, your stats.txt file gets erased every time again and again.
If you try to debug step by step your code, you can see that the first time you run the application, the file gets created with 0 size when you invoke openFileOutput
. You can check this from the DDMS File explorer.
So when you read it it holds nothing, and nothing is read by ReadItIn
. And when you write and close it, you can see from the DDMS File explorer that the file exists and has size > 0, rightly so.
But when you pass again by WriteItIn
, as soon as you invoke openFileOutput
, you can see from File explorer that the file size goes back to 0.
精彩评论