首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java文件下载器无法工作

Java文件下载器无法工作
EN

Stack Overflow用户
提问于 2013-07-28 12:53:37
回答 1查看 152关注 0票数 1

我创造了这个功能..。

代码语言:javascript
复制
void DownloadFromDatabase() throws IOException {
            URL website = new URL("http://theurlofmywebsite.org/databases/record_file.txt");

            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream("record_file.txt");

            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }

..。当我点击一个按钮的时候我就叫它,你可以在这里看到。

代码语言:javascript
复制
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

try {

            DownloadFromDatabase();

        } catch (IOException ex) {

           Logger.getLogger(xGrep.class.getName()).log(Level.SEVERE, null, ex);

        }
}

当我单击该按钮时,会调用DownloadFromDatabase();,但我看不到桌面上的文件record_file.txt。你知道为什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-28 13:23:07

这段代码不是最好的,但我已经在我的电脑上做了一个测试,它可以工作。它在2秒内下载500行文本文件。

代码语言:javascript
复制
void DownloadFromDatabase() throws MalformedURLException, IOException {

     URLConnection conn = new URL("your_url_here").openConnection();

     InputStream is = conn.getInputStream();
     OutputStream outstream = new FileOutputStream(new File("filename.txt"));

     byte[] buffer = new byte[4096];
     int len;

     while ((len = is.read(buffer)) > 0) {
      outstream.write(buffer, 0, len);
     }
     outstream.close();
     }

我把它命名为DownloadFromDatabase(),所以您只需复制/粘贴这段代码,而不是您的代码。另外,除了例外情况,也要注意。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17908410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档