直接从URL读取并写入文件 - Java [英] Read directly from a URL and write in a file - Java
问题描述
我正在阅读一个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); ((inputLine = br.readLine())!= null){
bw.write(inputLine + System.getProperty(line.separator));
}
br.close();
System.out.println(DONE);
$ b $ catch(IOException ioe){
ioe.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
返回本体;
$ / code $ / pre
$ b $ p请帮忙
解决方案问题是你正在使用一个BufferedWriter,你不关闭它。它的缓冲区中有一些内容不是在写,而是你不知道。
尝试刷新缓冲区并关闭BufferedWriter:
bw.flush();
bw.close();
包括这两行后面的br.close();。
你也可以阅读BufferedWriter如何工作 here。
我想你也应该关闭FileWriter,以解除阻止文件。 b $ b
fw.close();
编辑1:
关闭BufferedWriter将为您刷新缓冲区。您只需要关闭它。
I am reading the contents of a URL and write a file the problem is that I'm not able to write all the content in the file and do not know what I'm doing wrong.
My code,
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;
}
Please help
解决方案 The problem is you're using a BufferedWriter and you don't close it. It has some content in his buffer that is not writing and you're missing.
Try flushing the buffer and closing the BufferedWriter:
bw.flush();
bw.close();
Include this two lines after before your "br.close();".
Also you can read how BufferedWriter works here.
And I think you should close FileWriter too, in order to unblock the file.
fw.close();
EDIT 1:
Closing the BufferedWriter will flush the buffer for you. You need only to close it.
这篇关于直接从URL读取并写入文件 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!