直接从URL读取并写入文件

编程入门 行业动态 更新时间:2024-10-26 00:29:43
本文介绍了直接从URL读取并写入文件 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在阅读一个URL的内容,然后编写一个文件,问题是我无法写出文件中的所有内容,也不知道我在做什么错。

我的代码,

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); ((inputLine = br.readLine())!= null){ bw.write(inputLine + System.getProperty(line.separator)); } br.close(); System.out.println(DONE); $ b $ catch(IOException ioe){ ioe.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } 返回本体; $ / code $ / pre $ b $ p请帮忙

解决方案

问题是你正在使用一个BufferedWriter,你不关闭它。它的缓冲区中有一些内容不是在写,而是你不知道。

尝试刷新缓冲区并关闭BufferedWriter:

bw.flush(); bw.close();

包括这两行后面的br.close();。

你也可以阅读BufferedWriter如何工作 here。

我想你也应该关闭FileWriter,以解除阻止文件。 b $ b

fw.close();

编辑1:

关闭BufferedWriter将为您刷新缓冲区。您只需要关闭它。

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

解决方案

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.

更多推荐

直接从URL读取并写入文件

本文发布于:2023-07-16 07:24:34,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!