1

I've create this function...

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);
        }

... and I call it when I click a button as you can see here.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

try {

            DownloadFromDatabase();

        } catch (IOException ex) {

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

        }
}

When I click the button, DownloadFromDatabase(); is called but I don't see the file record_file.txt on my desktop. Do you know why?

4

1 回答 1

2

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

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()因此您只需复制/粘贴此代码而不是您的代码。另外,请注意例外情况。

于 2013-07-28T13:23:07.880 回答