0

インターネットでランダムなJavaコードを探していましたが、ダウンロードマネージャーのこのソースコードを見つけました。RandomAccessFileファイルのダウンロードに使用します。しかし、私が理解できなかったのは、どこにダウンロードするかということでした。ファイルをダウンロードする方法は次のとおりです。

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今日知ったばかりのクラスは初めてです。

4

2 に答える 2

3

現在の作業ディレクトリ(つまり、Javaコマンドを実行する場所)にダウンロードされ、ファイルの名前は。で指定されgetFileName(downloadLink)ます。

于 2012-08-19T23:26:38.757 に答える
0

私もこれは初めてです。getFileNameは同じクラス内のメソッドのようであり、そのコードがありません。

于 2013-01-16T22:17:17.510 に答える