2025-02-09

我在做一個項目時發現:
當我用常用的下載方法 下載xml到sd卡中 然後讀取xml解析時 總是有如下異常:


但程序仍能運行 隻是xml解析後的條數變少瞭 我覺得應該是解析過程中遇到瞭不能解析的字符
但檢查服務器端的xml並未發現錯誤 (我還曾一度認為是網絡不佳導致的,現在想象真是可笑的誤區)
之後我檢查瞭下載到本地sd卡的xml文件,用notepad打開後 錯誤發現瞭:


 經過百度 谷歌 的各種搜素也未找到緣由
我開始認為是我的下載與寫入sd 的方法有問題
但是從論壇或是文章中 看到很多下載文件與寫入的方法都是這樣的:
 
 
Java代碼 
    /**
     * 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; 
         
    } 
 
 
我是個初學者 也沒多想 就使用瞭這段代碼。但經過多次測試後發現
 
Java代碼 
byte buffer[] = new byte[1024]; 
            while(is.read(buffer) != -1){ 
                os.write(buffer); 
            } 
 這段代碼導致瞭下載後出現NUL符(有時xml較大時 會有部分亂碼 結尾不全的情況)
 
我換用瞭如下代碼(註釋的內容):
 
Java代碼 
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天的時間 又未在網上找到相應的解決辦法
為瞭方便和我一樣的菜鳥 大傢少走彎路 特寫瞭這篇文章!

作者“libo19881179”
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *