您的位置:首页 > 其它

终于搞出一个稳定的版本了……

2014-03-24 03:23 211 查看
bug大致都清掉了……

至少第一次运行是不会有bug了。

等会看能不能发github上去,然后直接外链到这边吧。

我花了一个周,就搞出了下载文件这么一个功能……

编程太难玩了。

package com.mlxy.xml;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.os.Environment;

import com.mlxy.util.CharacterProcesser;

/**
* XML文件下载器。
*
* @author mlxy
* */
public class XmlDownloader {
private Context parent;

private String city = CharacterProcesser.encodeByGB2312("南昌");
private String password = "DJOYnieT8234jlsK";
private int day = 0;
private String link = "http://php.weather.sina.com.cn/xml.php?city=" + city
+ "&password=" + password + "&day=" + day;

public XmlDownloader(Context parent) {
this.parent = parent;
}

/** 外部接口,根据设置好的类属性下载xml文件。*/
public void download() {
downloadAndVerifyXml(this.link);
}

/** 根据给定的链接下载对应的xml文件。
*
* @param link API的链接,需要标明网络协议。*/
private void downloadAndVerifyXml(String link) {
// 用链接字符串new出URL对象
URL url = null;
try {
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}

// 获取外部存储路径并创建文件对象。
File externalDirectory = Environment.getExternalStorageDirectory();
String fileName = "xml_resource.xml";
File file = new File(externalDirectory, fileName);

// 写文件。

// 初始化io流。
InputStream in = null;
BufferedReader reader = null;
FileOutputStream out = null;
BufferedWriter writer = null;

try {

// 建立连接并给io流赋值。
in = (InputStream) url.getContent();
reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"));
out = this.parent.openFileOutput(file.getName(), Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out, "iso-8859-1"));

// 读一行写一行,然后另起一行。
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
writer.flush();
writer.close();
out.close();
reader.close();
in.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

public XmlDownloader setCity(String city) {
this.city = city;
return this;
}
public String getCity() {
return this.city;
}

public XmlDownloader setPassword(String password) {
this.password = password;
return this;
}
public String getPassword() {
return this.password;
}

public XmlDownloader setDay(int day) {
this.day = day;
return this;
}
public int getDay() {
return this.day;
}

/** 获取API链接。*/
public String getLink() {
return this.link;
}
}


目前就这样
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: