我正在尝试使用android中的simple-framework来读取我从nasa feed获取的文件。 nasa文件在这里: http://www.nasa.gov/rss/dyn/image_of_the_day.rss
我解决这个问题的方法是使用以下代码:
Serializer serialezr = new Persister();
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/nasa";
try{
File dir = new File(file_path);
if(!dir.exists())
{
dir.mkdirs();
}
File nasa = new File(file_path,filename);
if(nasa.exists())
{
nasa.delete();
}
nasa.createNewFile();
source = new File(file_path + "/" + filename);
}
catch(Exception e)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
view.setText(sw.toString() + "here");
}
上面的代码在我稍后使用的目录中创建了nasa.xml文件
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
HttpResponse response = httpclient.execute(httpget);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
FileUtils.writeStringToFile(source,total.toString());
上面的代码实际上是使用DefaultHttpClient从他们的网站获取文件。
“谷歌搜索”我发现xml文件可能无法正确写入?查看来自美国国家航空航天局的xml文件,我看不到任何“<>”标签似乎是抛出此异常的最常见错误。
更新