因此,我的應用程序從肥皂服務器接收大型xml。我希望將其保存在一個文件中,以備後用。我設法做到這一點,並閱讀文件。但結果(閱讀後)是一個亂碼xml!來自xml後半部分的大部分文本(412個字符)被複制並粘貼到我的xml結尾,我無法弄清楚爲什麼會發生這種情況。 我已經嘗試了2種方法來編寫文件和2種方法來讀取文件,沒有骰子! (將在下面發佈代碼)注意:xml大5000-20000個字符,所以我使用方法來防止eclipse返回內存錯誤。保存/從文件中讀取大型xml字符串
底線:
- 輸入XML文件是正確的
- 輸出XML文件不正確
-tried 2保存方法
-tried 2讀取方法
- WTF?
保存代碼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();
保存代碼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();
讀取的代碼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);
讀碼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);
保存到文件中的代碼:
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();
對不起,長職位,但3天后,我在我束手無策。任何輸入都會很好,謝謝!
對不起,323go,一個從我逃走了。我刪除了其他6個或7不當Log.e的我之前發佈的代碼。 – Sebek 2013-03-28 09:31:13