对于一个项目,我需要解析XML文件。在本身的分析过程与文件,但我需要检索从URL文件。如何保存从URL到一个文件中的信息?
我已经尝试过很多,这里提供的答案,但因为现在没有工作的方式,我想他们。一个我想答案之一是以下几点:
public File createFile(URL url){
File f;
try {
f = new File(url.toURI());
} catch(URISyntaxException e) {
f = new File(url.getPath());
}
return f;
}
可悲的是这并没有解决问题,而是告诉我说:“URI方案不是‘文件’”
如果有人能帮助我与我的问题,我将非常感激。
使用Java IO,这将其保存到一个文件target.xml:
public File createFile(URL url) throws IOException {
File f = new File("C:\\Users\\my-user\\Desktop\\target.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
OutputStream outStream = new FileOutputStream(f);
String inputLine;
while ((inputLine = in.readLine()) != null) {
outStream.write(inputLine.getBytes());
}
outStream.close();
in.close();
return f;
}
我建议你使用Apache Commons IO库来获取你的URL的内容,你可以只用一行做到这一点:
IOUtils.toString(new URL("YOUR_URL_IN_HERE"), "UTF-8");
这将改变你的URL的内容为String
,你就可以写的内容到一个文件或处理任何你想要的其他流内容。
在这里,你可以找到docs of IOUtils