Android中下载文件并保存到SD卡

来源:互联网 发布:java 线程怎么实线的 编辑:程序博客网 时间:2024/05/17 23:52
package com.example.horizonscrollview;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.widget.LinearLayout;import android.widget.Toast;public class MainActivity extends Activity {    private LinearLayout llayout;    private String newpath;// 新建文件夹路径    private URL url;// 请求地址    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        init();        newSDFail();    }    @Override    protected void onStart() {        // TODO Auto-generated method stub        super.onStart();    }    private void init() {        // TODO Auto-generated method stub        this.llayout = (LinearLayout) findViewById(R.id.llayout_main);    }    private void dataImage() {    }    /**     * 判断SD卡是否插入     */    public String getSDPath() {        File SDdir = null;        boolean sdCardExist = Environment.getExternalStorageState().equals(                android.os.Environment.MEDIA_MOUNTED);        if (sdCardExist) {            SDdir = Environment.getExternalStorageDirectory();        }        if (SDdir != null) {            return SDdir.toString();        } else {            return null;        }    }    /**     * 创建一个文件夹     */    private void newSDFail() {        // TODO Auto-generated method stub        if (getSDPath() == null) {            Toast.makeText(MainActivity.this, "未找到SD卡", Toast.LENGTH_LONG)                    .show();        } else {            if (Environment.MEDIA_MOUNTED.equals(Environment                    .getExternalStorageState())) {                // 创建一个文件夹对象,赋值为外部存储器的目录                File SDCradlefail = Environment.getExternalStorageDirectory();// 当前SD卡目录                // 得到一个路径,目录为sdCard文件夹路径andName                newpath = SDCradlefail.getPath()                        + "/HorizonScrollview/tempimage/";                File path1 = new File(newpath);                if (!path1.exists()) {// if path no exist,else again create                    path1.mkdirs();                }            }        }    }    /**     * 写入文件     */    private void writeFile() {        // TODO Auto-generated method stub    }    public MainActivity() {        super();        // 得到当前外部存储设备的目录        // /SDCARD        newpath = Environment.getExternalStorageDirectory() + "/";    }    /**     * 在sd上创建文件     *      * @param fileName     * @return     * @throws IOException     */    public File creatSDFile(String fileName) throws IOException {        File file = new File(newpath + fileName);        file.createNewFile();        return file;    }    /**     * 在SD卡上创建目录     *      * @param dirName     * @return     */    public File creatSDDir(String dirName) {        File dir = new File(newpath + dirName);        dir.mkdir();        return dir;    }    /**     * 判断SD卡上的文件夹是否存在     */    public boolean isFileExist(String fileName) {        File file = new File(newpath + fileName);        return file.exists();    }    /**     * 将一个InputStream里面的数据写入到SD卡中     */    public File write2SDFromInput(String path, String fileName,            InputStream input) {        File file = null;        OutputStream output = null;        try {            creatSDDir(path);            file = creatSDFile(path + fileName);            output = new FileOutputStream(file);            byte buffer[] = new byte[4 * 1024];            while ((input.read(buffer)) != -1) {                output.write(buffer);            }            output.flush();        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                output.close();            } catch (Exception e) {                e.printStackTrace();            }        }        return file;    }    // 由于得到一个InputStream对象是所有文件处理前必须的操作,    // 所以将这个操作封装成了一个方法    public InputStream getInputStream(String urlStr) throws IOException {        InputStream is = null;        try {            url = new URL(urlStr);            HttpURLConnection urlConn = (HttpURLConnection) url                    .openConnection();            is = urlConn.getInputStream();        } catch (MalformedURLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return is;    }    // FileUtils fileUtils = new FileUtils();    public int downfile(String urlStr, String path, String fileName) {        if (this.isFileExist(path + fileName)) {            return 1;        } else {            try {                InputStream input = null;                input = getInputStream(urlStr);                File resultFile = this.write2SDFromInput(path, fileName, input);                if (resultFile == null) {                    return -1;                }            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        return 0;    }    /**     * 下载操作     */    private void downFile() {        // TODO Auto-generated method stub        // HttpDownloader httpDownLoader = new HttpDownloader();        int result = downfile("http://219.216.197.96:8080/test//file.jpg",                "test/", "test.jpg");        if (result == 0) {            Toast.makeText(MainActivity.this, "下载成功!", Toast.LENGTH_SHORT)                    .show();        } else if (result == 1) {            Toast.makeText(MainActivity.this, "已有文件!", Toast.LENGTH_SHORT)                    .show();        } else if (result == -1) {            Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_SHORT)                    .show();        }    }}
0 0
原创粉丝点击