Android 下载文件

如果是小的文件,可以直接使用 URLConnection.openStream() 打开网络输入流,然后将流写入到文件中


  1. 创建一个 空的 Android 项目 cn.twle.android.NormalDownload

  2. 修改 AndroidManifest.xml 添加相关权限

    <!-- 访问 internet 权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <!-- 往 SDCard 写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  3. 修改 activity_main.xml 创建布局

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="请输入要下载的文件地址" />
    
        <EditText
            android:id="@+id/editpath"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="https://www.twle.cn/static/i/meimei.jpg"
            />
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btndown"
            android:text="下载" />
    
        <TextView
            android:layout_marginTop="32dp"
            android:id="@+id/ms_log"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="" />
    </LinearLayout>
    
  4. 修改 MainActivity.java

    package cn.twle.android.normaldownload;
    
    import java.io.InputStream;
    import java.io.RandomAccessFile;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
        private TextView ms_log;
        private EditText editpath;
        private Button btndown;
    
        private StringBuilder sb;
    
        private Handler handler = new UIHander();
    
        private final class UIHander extends Handler {
            public void handleMessage(Message msg) {
                ms_log.setText(sb.toString());
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            sb = new StringBuilder();
    
            ms_log = (TextView) findViewById(R.id.ms_log);
            editpath = (EditText) findViewById(R.id.editpath);
            btndown = (Button) findViewById(R.id.btndown);
    
            btndown.setOnClickListener(new View.OnClickListener() {
    
                public void onClick(View v) {
    
                    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        sendMessage("sd卡读取失败\n");
                        return;
                    }
    
                    final String path = editpath.getText().toString();
                    final String filename = "meimei.jpg";
                    final String saveDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                    final String savePath = saveDir + "/" + filename;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
    
                            try {
                                URL url = new URL(path);
                                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                                conn.setConnectTimeout(5000);
                                conn.setRequestMethod("GET");
    
                                //获得需要下载的文件的长度(大小)
                                int filelength = conn.getContentLength();
    
                                sendMessage("文件总大小" + filelength + "\n");
                                sendMessage("文件保存地址: " + saveDir + "/" + filename + "\n");
    
                                //生成一个大小相同的本地文件
                                RandomAccessFile file = new RandomAccessFile(savePath, "rwd");
                                file.setLength(filelength);
    
                                InputStream is = url.openStream();
    
                                byte[] buffer = new byte[1024];
                                int len = 0;
    
                                //从输入六中读取数据,读到缓冲区中
                                while((len = is.read(buffer)) > 0)
                                {
    
                                    file.write(buffer,0,len);
                                }
    
                                sendMessage("文件下载完成\n");
                                //关闭输入输出流
                                is.close();
                                file.close();
                                conn.disconnect();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
    
            });
        }
    
        public void sendMessage(String msg) {
    
            sb.append(msg);
    
            handler.sendEmptyMessage(0x001);
        }
    }
    

Android 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.