我在做一个项目时发现:当我用常用的下载方法 下载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;
- }
/** * 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);
- }
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);
- }
byte buffer[] = new byte[1024]; int bufferLength = 0; while ( (bufferLength = is.read(buffer)) > 0 ) { os.write(buffer, 0, bufferLength); }
便解决了 上述问题
我是个菜鸟 如果说原因我只能猜测 可能是错误的写法每次写入固定1024的长度
而换用有bufferLength的方法write 则规定了长度 避免了不足1024的用NUL代替了吧!
转载于:https://blog.51cto.com/gswxr/716240