Read directly from a URL and write in a file - Jav

2019-06-01 03:52发布

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

标签: java file url
2条回答
叛逆
2楼-- · 2019-06-01 04:25

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:

final Path path = file.toPath(); // or rather use Path directly
Files.createDirectories(path.getParent());

try (
    final InputStream in = conn.getInputStream();
) {
    Files.copy(in, path);
}

Done, encoding independent, and all resources closed.

查看更多
放我归山
3楼-- · 2019-06-01 04:39

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.

查看更多
登录 后发表回答