http://androiddada.iteye.com/
我在做一個項目時發現:
當我用常用的下載方法 下載xml到sd卡中 然後讀取xml解析時 總是有如下異常:
但程序仍能運行 只是xml解析後的條數變少了 我覺得應該是解析過程中遇到了不能解析的字符
但檢查服務器端的xml並未發現錯誤 (我還曾一度認爲是網絡不佳導致的,現在想象真是可笑的誤區)
之後我檢查了下載到本地sd卡的xml文件,用notepad打開後 錯誤發現了:
經過百度 谷歌 的各種搜素也未找到緣由
我開始認爲是我的下載與寫入sd 的方法有問題
但是從論壇或是文章中 看到很多下載文件與寫入的方法都是這樣的:
/**
* is流寫入sd卡
* @param path
* @param fileName 路徑+名字
* @param is
* @return
*/
public File write2SDFromIS(String path,String fileName,InputStream is){
File file = null;
OutputStream os = null;
try {
createSDDir(path);
file = createSDFile(path+fileName);
os = new FileOutputStream(file);
byte buffer[] = new byte[1024];
while(is.read(buffer) != -1){
os.write(buffer);
}
// int bufferLength = 0;
// while ( (bufferLength = is.read(buffer)) > 0 ) {
// os.write(buffer, 0, bufferLength);
// }
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
我是個初學者 也沒多想 就使用了這段代碼。但經過多次測試後發現
byte buffer[] = new byte[1024];
while(is.read(buffer) != -1){
os.write(buffer);
}
這段代碼導致了下載後出現NUL符(有時xml較大時 會有部分亂碼 結尾不全的情況)
我換用瞭如下代碼(註釋的內容):
byte buffer[] = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = is.read(buffer)) > 0 ) {
os.write(buffer, 0, bufferLength);
}
便解決了 上述問題
我是個菜鳥 如果說原因我只能猜測 可能是錯誤的寫法每次寫入固定1024的長度
而換用有bufferLength的方法write 則規定了長度 避免了不足1024的用NUL代替了吧!
因爲這個問題困擾了我3天的時間 又未在網上找到相應的解決辦法
爲了方便和我一樣的菜鳥 大家少走彎路 特寫了這篇文章!
http://androiddada.iteye.com/