1

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();
4

2 回答 2

1

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.

于 2013-05-21T18:52:04.593 回答
1

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);
        }
    }
于 2013-05-21T21:38:30.230 回答