问题描述
我正在Internet上浏览随机Java代码,并且发现了下载管理器.它使用 RandomAccessFile
下载文件.我无法确定的一件事是它将下载到何处.这是下载文件的方法:
I was browsing the Internet for random Java code, and I found this source code for a download manager. It uses RandomAccessFile
to download the files. The one thing I could not figure out though, was where it would download to. Here is the method that downloads the file:
public void startDownload() {
System.out.println("Starting...");
RandomAccessFile file = null;
InputStream stream = null;
try {
URL downloadLink = new URL("http://www.website.com/file.txt");
// Open the connection to the URL
HttpURLConnection connection = (HttpURLConnection) downloadLink.openConnection();
// Specify what portion of file to download
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
// Connect to the server
connection.connect();
// Make sure the code is in the 200 range
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
// Set the size for the download if it hasn't been already set
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it
file = new RandomAccessFile(getFileName(downloadLink), "rw");
// getFileName returns the name of the file mentioned in the URL
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
System.out.println("Progress: " + getProgress() + "%");
// Size the buffer according to how much of the file is left to download
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from the server into the buffer
int read = stream.read(buffer);
if (read == -1) {
break;
}
// Write buffer to file
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close the stream and RAF
}
System.out.println("Done!");
}
很抱歉,如果这很明显.我是今天刚学到的 RandomAccessFile
类的新手.
I am sorry if this is obvious. I am new to the RandomAccessFile
class, as I just learned of it today.
推荐答案
它将下载到当前工作目录(即运行Java命令的位置)中,文件名将由 getFileName(downloadLink)
.
It will download it in the current working directory (i.e. where you run your java command) and the name of the file will be given by getFileName(downloadLink)
.
这篇关于使用RandomAccessFile通过Internet下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!