获取xml的inputstream代码:
 public static InputStream getStream(String path) {   
     /**  
         * 得到数据  
         * @param args  
         * @return  
         */   
            InputStream stream = null;   
          
            URL url;
     try {
     url = new URL(path);
     //得到打开的链接对象   
             HttpURLConnection conn = (HttpURLConnection)url.openConnection();   
             conn.setRequestMethod("GET");
             conn.setReadTimeout(5*1000); 
             conn.setConnectTimeout(5*1000);
             //设置请求超时与请求方式  
             
             stream = conn.getInputStream();
             
     } catch (MalformedURLException e) {
    
     // TODO Auto-generated catch block
     e.printStackTrace();
     }catch (ProtocolException e) {
    
     // TODO Auto-generated catch block
     e.printStackTrace();
     }catch (IOException e) {
    
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
                return stream;
    }存储到手机卡上的代码:public static void write2SDFromInput(String path, String name,InputStream inputStream) {
File file = new File(path + name);
OutputStream output = null;
try {
File file1 = new File(path);
// 判断SD卡中目录是否存在
if ( !file1.exists()) {
System.out.println("creatdir:----------------");
file1.mkdirs();
}
if ( !file.exists()) {
System.out.println("creatfile:------------------");
file.createNewFile();
}
output = new FileOutputStream(file);
byte buffer [] = new byte[1 * 1024];
while((inputStream.read(buffer)) != -1){
output.write(buffer);
}
output.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}这两端代码我都是很通用的代码,没有什么问题啊。得到的inputstream直接用dom4j解析没问题。但是我存到SD卡之后再读取我在程序里面解析出现错误,是xml的格式错误。导出来一看在后面多了一些内容。这个xml需要备份一下,有什么办法能把这个xml保存下了?望不吝指教,多谢。

解决方案 »

  1.   

    byte buffer [] = new byte[1 * 1024];
    while((inputStream.read(buffer)) != -1){
    output.write(buffer);
    改成
    byte buffer [] = new byte[1 * 1024];
    int length = 0;
    while((length = inputStream.read(buffer)) > 0) {
        output.write(buffer,0,length);
    }
    你那样相当于每次往xml文件中写入1024byte,即使文件最后只剩几十byte你还是写入1024,那样文件就错了