So, my app receives a large xml from a soap server. I wish to save this in a file, for later use. I managed to do this, and to read the file. BUT the result (after reading) is a garbled xml! A large portion of text (412 characters) from the latter part of the xml is copied and pasted at the end of my xml, and I can't figure out why this is happening. I have tried 2 ways to write the file and 2 ways to read the file, no dice! (will post code below) Note: xml is large 5000-20000 characters, so I used methods to keep eclipse from returning out of memory error.
BOTTOM LINE:
-input xml file is correct
-output xml file is incorrect
-tried 2 save methods
-tried 2 read methods
-wtf?!
save code 1:
InputStream is = new ByteArrayInputStream(string.getBytes());
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
is.close();
save code 2 :
InputStream is = new ByteArrayInputStream(string.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
Log.e("stuff is good", "line: "+line);
sb.append(line);
if (sb.toString().length() > 10000) {
fos.write(sb.toString().getBytes());
fos.flush();
sb = new StringBuilder();
}
}
fos.write(sb.toString().getBytes());
fos.flush();
is.close();
fos.close();
read code 1:
FileInputStream fis = openFileInput("caca");
int c;
StringBuilder fileContent = new StringBuilder();
while((c=fis.read())!=-1)
{
fileContent.append((char)c);
}
fis.close();
Log.e("TEST TEST", "XML length = "
+String.valueOf(fileContent.length()) );
Log.e("TEST TEST", "XML = "
+fileContent );
read code 2 :
FileInputStream fis;
fis = openFileInput("caca");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
int i =1;
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
Log.v("TEST"+ String.valueOf(i), new String(buffer) );
i++;
}
Log.e("TEST TEST", "XML length = "
+String.valueOf(fileContent.length()) );
Log.e("TEST TEST", "XML = "
+fileContent );
save to file code :
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(fileContent);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Sorry for the long post, but after 3 days, I'm at my wits end. Any input would be nice, thank you!