我已创建此功能......
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);
}
...当我点击按钮时我会打电话给你。
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
。你知道为什么吗?
答案 0 :(得分: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()
,因此您只需复制/粘贴此代码而不是您的代码。另外,请注意例外情况。