Java to download a file from internet

本文介绍了使用Java进行在线图片下载的三种方法:通过Java NIO的transferFrom方法高效传输文件;利用Apache Commons IO库简化代码;以及采用传统的输入输出流方式逐字节读取并保存文件。

    There is an Online file (such as https://i-blog.csdnimg.cn/blog_migrate/d58c352ff5383460ed180137ba09132b.gif),as below:

    

If you wan to download this picture,how can we grap and save to a directory?

ok,here have some ways as below:


The first way

 using the Java NIO,here is the main code snippet:

import java.net.*;
import java.nio.channels.*;
import java.io.*;
public class download {
	 public static void main(String[] args) {
	       
	        
	        try {
				URL website=new URL("https://i-blog.csdnimg.cn/blog_migrate/d58c352ff5383460ed180137ba09132b.gif");
				ReadableByteChannel rbc=Channels.newChannel(website.openStream());
				FileOutputStream fos = new FileOutputStream("C://information.html");
				fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
}

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.

Check more about it here.

Note: The third parameter in transferFrom is the maximum number of bytes to transfer. Integer.Max_VALUE will transfer at most 2^31 bytes, Long.MAX_VALUE will allow at most 2^63 bytes (larger than any file in existence).

Build and run! Very cool, the result as below:



The seconed way:

use apache commons-io,just one line code,as below:
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

Take note that  copyURLToFile  with timeout parameter is only available since version 2.0 of Commons IO library. See  Java docs

The Third way:

Downloading a file requires you to read it, either way you will have to go through the file in some way. Instead of line by line, you can just read it by bytes from the stream:

import java.io.*;
import java.net.*;

public class filedown {
    public static void download(String address, String localFileName) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;

        try {
            URL url = new URL(address);
            out = new BufferedOutputStream(new FileOutputStream(localFileName));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];

            int numRead;
            long numWritten = 0;

            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
            }

            System.out.println(localFileName + "\t" + numWritten);
        } 
        catch (Exception exception) { 
            exception.printStackTrace();
        } 
        finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } 
            catch (IOException ioe) {
            }
        }
    }

    public static void download(String address) {
        int lastSlashIndex = address.lastIndexOf('/');
        if (lastSlashIndex >= 0 &&
        lastSlashIndex < address.length() - 1) {
            download(address, address.substring(lastSlashIndex + 1));
        } 
        else {
            System.err.println("Could not figure out local file name for "+address);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            download(args[i]);
        }
    }
}

If in.close throws an exception, out.close is not called.You'll need to handle exceptions, probably external to this method.  Using a BufferedInputStream can sometimes lead to SocketTimeoutException being thrown. Replace it byInputStream and you should be ok. Here are some background details:stackoverflow.com/questions/2964044/…


Finally:


Personally, I've found Apache's HttpClient to be more than capable of everything I've needed to do with regards to this. Here is a great tutorial on using HttpClient. Hope this post can help you! 

Last But no Least:if you have any issues,you can  check my blog,thinks your attention !

Lab 1 - Chapter 1 Java Language Programming | Chapter 1: Foundations of Java and First Steps Course: Java Language Programming Instructor: Ahsan Shehzad Date: September 1, 2025 Lab Objective: Your First Java Program ✅ Goal By the end of this lab, you will have a fully functional Java development environment and will have successfully written, compiled, and run the "Hello, World!" program for our course project, MyContactManager . Prerequisites A computer with a modern operating system (Windows, macOS, or Linux). An active internet connection to download the required software. Final Result Step 1: Install the Java Development Kit (JDK) Goal Install the core toolkit that allows us to build and run Java applications. Instructions 1. Navigate to a trusted OpenJDK distributor like Adoptium. 2. Download the latest LTS (Long-Term Support) version installer for your operating system (e.g., Temurin 17 or 21). 3. Run the installer and follow the on-screen prompts, accepting the default settings. Ensure the "Add to PATH" option is checked if available. Verification Code Open a new terminal or command prompt after the installation is complete and run these commands:Expected Result The terminal should print the installed Java version (e.g., openjdk version "17.0.8" ). If you see an error like 'command not found' , your system's PATH variable may be misconfigured. Please ask for assistance. Step 2: Install a Professional IDE Goal Install IntelliJ IDEA, a powerful Integrated Development Environment (IDE) that will help us write, manage, and debug our code efficiently. Instructions 1. Go to the official JetBrains website: jetbrains.com/idea/download/. 2. Download the installer for the Community Edition, which is free. 3. Run the installer, accepting the default options. You can create a desktop shortcut for convenience. Expected Result The IntelliJ IDEA application should now be installed on your computer. You can launch it from your applications folder, desktop, or start menu. Step 3: Create the 'MyContactManager' Project Goal Create a new, organized project inside IntelliJ to house all the code for our course application. Instructions 1. Launch IntelliJ IDEA. If prompted, you can skip the initial configuration plugins. 2. On the welcome screen, click "New Project". 3. In the New Project window: Enter the Name: MyContactManager Set the Language: Java Set the Build system: IntelliJ For JDK: Select the JDK you just installed from the dropdown. It should be detected automatically. 4. Click "Create". # Check the Java Runtime Environment version java -version # Check the Java Compiler version javac -version 1 2 3 4 5Expected Result IntelliJ will create a project structure. In the Project Explorer pane on the left, you'll see a folder named src . This src (source) folder is where all of our .java files will live. Step 4: Write and Run the main Class Goal Write the entry point for our application and execute it to see output. Instructions 1. In the Project Explorer, right-click the blue src folder. 2. Select New -> Java Class . 3. In the pop-up, enter the name MyContactManager and press Enter. 4. Type (or copy) the following code into the editor window that appears. 5. To run the program, click the green play button ▶ that appears to the left of the public static void main line. Code Expected Result A "Run" tool window will appear at the bottom of IntelliJ, and you should see the following text output: Welcome to MyContactManager! /** * The main class for our MyContactManager application. * This class serves as the entry point for the program. */ public class MyContactManager { /** * The main method is automatically executed when the program runs. * @param args Command-line arguments (we will ignore these for now). */ public static void main(String[] args) { // System.out.println() is a built-in Java command // to print a line of text to the console. System.out.println("Welcome to MyContactManager!"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Step 5: Experiment and See an Error Goal Understand how the compiler helps us by catching syntax errors before the program runs. Instructions 1. Introduce an error: In your MyContactManager.java file, deliberately delete the semicolon ( ; ) at the end of the System.out.println(...) line. 2. Observe the IDE: Notice how IntelliJ immediately underlines the code in red and shows an error message if you hover over it. This is called real-time error checking, a key feature of an IDE. 3. Attempt to run: Click the green play button ▶ again. Erroneous Code Expected Result The program will fail to compile. The "Run" window will show a compile-time error, which will read something like java: ';' expected . This demonstrates how the compiler acts as a strict grammar checker for the Java language, preventing broken code from ever running. Simply add the semicolon back to fix it. 🚀 Challenges Finished the lab early? Try these small challenges to solidify your understanding. 1. Personalize It Modify the program to print a personalized welcome message, like "Hello, [Your Name]!" . 2. Multi-Line Output Add a second System.out.println() statement on a new line to print a description of the application, such as "This app will help you manage your contacts." . 3. Explore an IDE Warning The String[] args parameter in the main method is currently grayed out. Hover over it. The IDE is telling you it's an "unused parameter." This isn't an error, but a friendly warning that you've declared something you never use. public class MyContactManager { public static void main(String[] args) { // This line now has a deliberate syntax error! System.out.println("Welcome to MyContactManager!") // <-- Missing semicolon } } 1 2 3 4 5 6 答案是什么
最新发布
09-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微个日光日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值