Reputation: 808
I've written a code that reads web pages and transfers them into a .txt file. The problem is that the output file (something.txt) is LOCKED (I use OS X if that helps). I figured out that there could be a problem with unclosed BufferedReader(), but it seems closed. Thanks.
PrintStream ps = new PrintStream(new File("/Users/MyName/Desktop/something.txt"));
URL myUrl = new URL("webPage");
BufferedReader in = new BufferedReader(new InputStreamReader(myUrl.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
ps.println(inputLine);
System.out.println(inputLine);
}
in.close();
ps.close();
Upvotes: 1
Views: 198
Reputation: 135992
If you are in Java 7 then the best way is try-with-resources
which guarantees that both in
and ps
will be closed
try (PrintStream ps = new PrintStream(new File("/Users/MyName/Desktop/something.txt"));
BufferedReader in = new BufferedReader(new InputStreamReader(
new URL("webPage").openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
ps.println(inputLine);
System.out.println(inputLine);
}
}
Upvotes: 1
Reputation: 23219
Maybe there's an exception between thrown in your read/write loop. If that happens the close()
calls will not happen which would explain your issue, if you are re-using the same filenames within a single run of your program.
To fix that do the close()
in a finally block with the try wrapping the read/write loop.
Upvotes: 1