我正在读取URL的内容并写一个文件,问题是我无法写入文件中的所有内容,也不知道我做错了什么.
我的代码,
try {
URL url = new URL(sourceUri);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
file.getParentFile().mkdirs();
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
while ((inputLine = br.readLine()) != null) {
bw.write(inputLine + System.getProperty("line.separator"));
}
br.close();
System.out.println("DONE");
}catch (IOException ioe){
ioe.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return ontologies;
}
Run Code Online (Sandbox Code Playgroud)
请帮忙
你做错了很多事.
第一:你没有关闭所有资源; 文件的作者在哪里关闭?
第二:你使用时new InputStreamReader(...)没有指定编码.是什么说另一端的编码是你的JVM/OS组合之一?
最后但并非最不重要,事实上,这是最重要的,你应该使用java.nio.file.毕竟这是2015年.
简单方案:
final Path path = file.toPath(); // or rather use Path directly
Files.createDirectories(path.getParent());
try (
final InputStream in = conn.getInputStream();
) {
Files.copy(in, path);
}
Run Code Online (Sandbox Code Playgroud)
完成,编码独立,并关闭所有资源.