Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8009403
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T18:26:25+00:00 2026-06-04T18:26:25+00:00

I wrote a thread program in Java to download a file from URL (https).

  • 0

I wrote a thread program in Java to download a file from URL (https). Sometimes the size of the file downloaded is reduced from its original size.

How to download file without losing data?

Code

public class Download extends Observable implements Runnable {
    private static final int MAX_BUFFER_SIZE = 1024;        
    public static final int DOWNLOADING = 0;    
    public static final int PAUSED = 1; 
    public static final int COMPLETE = 2;   
    public static final int CANCELLED = 3;  
    public static final int ERROR = 4;  
    private URL url; 
    private int size; 
    private int downloaded; 
    private int status; 
    
    public Download(URL url){
        this.url = url;
        size=-1;
        downloaded=0;
        status=DOWNLOADING;
        download();
    }
    
    public String getURL(){
        return url.toString();
    }   
    
    public void error(){
        status = ERROR;
        stateChanged();
    }
    
    private void download(){
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {     
        RandomAccessFile randomAccessFile = null;
        InputStream inputStream = null;
        try{
            HttpsURLConnection connection = getSSLCertficate(getURL());
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range","bytes=" + downloaded + "-");
            connection.connect();
            if(connection.getResponseCode()/100 != 2){
                error();
            }
            int contentLength = connection.getContentLength();
            if(contentLength <1){
                error();
            }
            if(size == -1){
                size = contentLength;
                stateChanged();
            }
            randomAccessFile = new RandomAccessFile("/home/user/Desktop/dotproject-2.1.5.tar.gz","rw");         
            randomAccessFile.seek(downloaded);
            inputStream = connection.getInputStream();
            while(status == DOWNLOADING){
                byte buffer[];
                int finalSize=size - downloaded;
                if ( finalSize > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                int read = inputStream.read(buffer);
                if(read == -1)
                    break;              
                
                randomAccessFile.write(buffer, 0, read);                
                downloaded += read;             
                stateChanged();
            }           
            
        }catch (Exception e) {
            
        }
    }
    
    private void stateChanged(){
        setChanged();
        notifyObservers();
    }
    
    private HttpsURLConnection getSSLCertficate(String urlPath) throws NoSuchAlgorithmException, KeyManagementException, IOException{
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0],new TrustManager[]{new DefaultTrustManager()},new SecureRandom());
        SSLContext.setDefault(ctx);
        
        URL url = new URL(urlPath);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            
            @Override
            public boolean verify(String arg0, SSLSession arg1) {               
                return true;
            }
        });
        
        return conn;
    }

    public static void main(String[] args) throws MalformedURLException {
        Download d = new Download(new URL("https://192.16.1.130/Source.tar.gz"));
        d.run();
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T18:26:27+00:00Added an answer on June 4, 2026 at 6:26 pm

    Please close your input stream in finally section (than it automatically flush all data):

    try {
        ....
    } catch(...) {
        ...
    } finally {
        // This will guaranty you get all data:
        inputStream.close();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote a simple program with java swing which suppose to start another thread
I wrote a Java program to add and retrieve data from an MS Access.
I'm trying to understand concurrency in Go. In particular, I wrote this thread-unsafe program:
Actually I wrote a Java program for calculating a particular number on the Fibonacci
I am new to Java Multithreading World, I wrote this program, I just wanted
I wrote a Multithreaded program in Java given below :- public class Client {
I wrote a java program that should fill a sqlite database with some rows
I wrote a server-client communication program and it worked well. Client module import java.io.*;
One of the users of a Java swing GUI program that I wrote is
I recently inherited a small Java program that takes information from a large database,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.