This question already has an answer here:
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
You are doing many things incorrectly.
First: you don't close all your resources; where is the writer to the file closed?
Second: you use
new InputStreamReader(...)
without specifying the encoding. What says that the encoding on the other end is the one of your JVM/OS combination?Last but not least, and in fact, this is the most important, you should use java.nio.file. This is 2015 after all.
Simple solution:
Done, encoding independent, and all resources closed.
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
: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.EDIT 1:
Closing the
BufferedWriter
will flush the buffer for you. You need only to close it.