从网络下载xml保存到SD卡后出现多余的内容,请教原因?

summersrest 2012-09-11 10:46:53
获取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保存下了?望不吝指教,多谢。
...全文
74 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Utopia 2012-09-11
  • 打赏
  • 举报
回复
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,那样文件就错了
summersrest 2012-09-11
  • 打赏
  • 举报
回复
[Quote=引用 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(buff……
[/Quote]
明白了,我应该想到的啊!特别感谢这位兄台。真的特别感谢。

80,362

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧