Reputation: 5013
I'm looking to read the contents of a URL and write them to file, this is working as expected but it's only writing it a single time even though the program console shows multiple lines.
Code:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(true) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.close();
The data in the URL refreshes constantly so there should be different data each time as the console print shows but it's only writing the first instance to file.
Upvotes: 0
Views: 47
Reputation: 1
If you want to append file each time you have to flush writer instead of closing and close at the end.
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
while(condition) {
URL oracle = new URL("https://linkToData.com");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
writer.println(inputLine);
System.out.println(inputLine);
}
writer.flush();
}
writer.close();
Upvotes: 0
Reputation: 577
The key is writer.close()
! If you want to write the file anew every time, you have to reopen the Writer
each time.
Upvotes: 1