Monday, July 21, 2025

Java Download

# Loading Files Over Network in Java

Here's how to load files from a network connection in Java, covering several common scenarios:

## 1. Basic HTTP File Download

```java
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class HttpFileDownloader {
    public static void main(String[] args) {
        String fileUrl = "https://example.com/file.txt";
        String localFilePath = "downloaded_file.txt";
        
        try (InputStream in = new URL(fileUrl).openStream()) {
            Files.copy(in, Paths.get(localFilePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File downloaded successfully!");
        } catch (IOException e) {
            System.err.println("Error downloading file: " + e.getMessage());
        }
    }
}
```

## 2. HTTP Download with Progress Monitoring

```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloadWithProgress {
    public static void downloadFile(String fileURL, String savePath) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        
        int fileSize = httpConnection.getContentLength();
        System.out.println("File size: " + fileSize + " bytes");
        
        try (InputStream input = new BufferedInputStream(httpConnection.getInputStream());
             OutputStream output = new FileOutputStream(savePath)) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            long totalRead = 0;
            
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
                totalRead += bytesRead;
                
                // Calculate and display progress
                int progress = (int) ((totalRead * 100) / fileSize);
                System.out.print("\rDownload progress: " + progress + "%");
            }
            System.out.println("\nDownload complete!");
        }
    }

    public static void main(String[] args) {
        try {
            downloadFile("https://example.com/largefile.zip", "downloaded.zip");
        } catch (IOException e) {
            System.err.println("Download failed: " + e.getMessage());
        }
    }
}
```

## 3. FTP File Download

```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.*;

public class FtpFileDownloader {
    public static void main(String[] args) {
        FTPClient ftpClient = new FTPClient();
        
        try {
            // Connect to server
            ftpClient.connect("ftp.example.com", 21);
            ftpClient.login("username", "password");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            
            // Download file
            String remoteFile = "/public/file.txt";
            File localFile = new File("local_file.txt");
            
            try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile))) {
                boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
                if (success) {
                    System.out.println("File downloaded successfully!");
                } else {
                    System.err.println("File download failed");
                }
            }
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
```

## 4. Downloading JSON/Text Data from API

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiDataDownloader {
    public static String getJsonFromUrl(String urlToRead) throws Exception {
        StringBuilder result = new StringBuilder();
        URL url = new URL(urlToRead);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        try {
            String json = getJsonFromUrl("https://api.example.com/data");
            System.out.println("Received JSON data:");
            System.out.println(json);
        } catch (Exception e) {
            System.err.println("Error fetching data: " + e.getMessage());
        }
    }
}
```

## 5. Secure Download (HTTPS with SSL)

```java
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SecureFileDownloader {
    public static void downloadHttpsFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        
        // Optional: Configure SSL (if needed for custom certificates)
        // SSLContext sslContext = SSLContext.getInstance("TLS");
        // sslContext.init(null, new TrustManager[]{new CustomTrustManager()}, null);
        // connection.setSSLSocketFactory(sslContext.getSocketFactory());
        
        try (InputStream in = connection.getInputStream()) {
            Files.copy(in, Paths.get(savePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Secure file downloaded successfully!");
        }
    }

    public static void main(String[] args) {
        try {
            downloadHttpsFile("https://example.com/securefile.pdf", "secure_file.pdf");
        } catch (IOException e) {
            System.err.println("Secure download failed: " + e.getMessage());
        }
    }
}
```

## Important Considerations:

1. **Error Handling**: Always implement proper error handling for network operations
2. **Timeouts**: Set connection and read timeouts
   ```java
   connection.setConnectTimeout(5000); // 5 seconds
   connection.setReadTimeout(15000);    // 15 seconds
   ```
3. **Authentication**: For protected resources, add proper authentication headers
4. **Large Files**: For large files, consider:
   - Streaming instead of loading into memory
   - Resumable downloads
5. **Permissions**: Add required permissions in Android:
   ```xml
   <uses-permission android:name="android.permission.INTERNET" />
   ```

Would you like me to explain any specific part in more detail or cover additional network file loading scenarios?

No comments: