zoukankan      html  css  js  c++  java
  • Android之访问下载文件

    1.SD卡操作类 FileUtils.java

    package com.example.mars_1500_download;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import android.os.Environment;
    
    public class FileUtils {
        private String SDPATH;
    
        public String getSDPATH() {
            return SDPATH;
        }
        public FileUtils() {
            //得到当前外部存储设备的目录
            // /SDCARD
            SDPATH = Environment.getExternalStorageDirectory() + "/";
        }
        /**
         * 在SD卡上创建文件
         * 
         * @throws IOException
         */
        public File creatSDFile(String fileName) throws IOException {
            File file = new File(SDPATH + fileName);
            file.createNewFile();
            return file;
        }
        
        /**
         * 在SD卡上创建目录
         * 
         * @param dirName
         */
        public File creatSDDir(String dirName) {
            File dir = new File(SDPATH + dirName);
            dir.mkdirs();
            return dir;
        }
    
        /**
         * 判断SD卡上的文件夹是否存在
         */
        public boolean isFileExist(String fileName){
            File file = new File(SDPATH + 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;
        }
    
    }

    2.下载类HttpDownloader

    package com.example.mars_1500_download;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class HttpDownloader {
        private URL url = null;
    
        /**
         * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 1.创建一个URL对象
         * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStram 4.从InputStream当中读取数据
         * 
         * @param urlStr
         * @return
         */
        public String download(String urlStr) {
            StringBuffer sb = new StringBuffer();
            String line = null;
            BufferedReader buffer = null;
            try {
                // 创建一个URL对象
                url = new URL(urlStr);
                // 创建一个Http连接
                HttpURLConnection urlConn = (HttpURLConnection) url
                        .openConnection();
                // 使用IO流读取数据
                buffer = new BufferedReader(new InputStreamReader(
                        urlConn.getInputStream()));
                while ((line = buffer.readLine()) != null) {
                    sb.append(line);
                }
            } catch (Exception e) {
                System.out.println("download:" + e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    buffer.close();
                } catch (Exception e) {
                    System.out.println("download buffer.close():" + e.getMessage());
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    
        /**
         * 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
         */
        public int downFile(String urlStr, String path, String fileName) {
            InputStream inputStream = null;
            try {
                FileUtils fileUtils = new FileUtils();
    
                if (fileUtils.isFileExist(path + fileName)) {
                    return 1;
                } else {
                    inputStream = getInputStreamFromUrl(urlStr);
                    File resultFile = fileUtils.write2SDFromInput(path, fileName,
                            inputStream);
                    if (resultFile == null) {
                        return -1;
                    }
                }
            } catch (Exception e) {
                System.out.println("downFile:" + e.getMessage());
                e.printStackTrace();
                return -1;
            } finally {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    System.out.println("downFile close:" + e.getMessage());
                    e.printStackTrace();
                }
            }
            return 0;
        }
    
        /**
         * 根据URL得到输入流
         * 
         * @param urlStr
         * @return
         * @throws MalformedURLException
         * @throws IOException
         */
        public InputStream getInputStreamFromUrl(String urlStr)
                throws MalformedURLException, IOException {
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            InputStream inputStream = urlConn.getInputStream();
            return inputStream;
        }
    }

    3.下载文件Activity

    package com.example.mars_1500_download;
    
    import android.support.v7.app.ActionBarActivity;
    import android.support.v7.app.ActionBar;
    import android.support.v4.app.Fragment;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.os.Build;
    
    public class MainActivity extends Activity {
        private Button downloadTxtButton;
        private Button downloadMp3Button;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            downloadTxtButton=(Button)findViewById(R.id.downloadTxtButton);
            downloadMp3Button=(Button)findViewById(R.id.downloadMp3Button);
            downloadTxtButton.setOnClickListener(new DownloadTxtListener());
            downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
            
            /*if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment()).commit();
            }*/
        }
    
        class DownloadTxtListener implements OnClickListener
        {
            @Override
            public void onClick(View v) {
                System.out.println("txt");
                HttpDownloader httpDownloader=new HttpDownloader();
                String lrc=httpDownloader.download("http://www.cnblogs.com/zhuawang/p/3648551.html");
                System.out.println(lrc);
            }
        }
        
        class DownloadMp3Listener implements OnClickListener
        {
            @Override
            public void onClick(View v) {
                HttpDownloader httpDownloader=new HttpDownloader();
                int ret=httpDownloader.downFile("http://www.cnblogs.com/zhuawang/p/3648551.html","voa/","a.html");
                System.out.println(ret);
            }
        }
        
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
    
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
        /**
         * A placeholder fragment containing a simple view.
         */
        public static class PlaceholderFragment extends Fragment {
    
            public PlaceholderFragment() {
            }
    
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container,
                        false);
                return rootView;
            }
        }
    
    }

    4.设置权限

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mars_1500_download"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
    android:name="com.example.mars_1500_download.MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>

    </application>


    <!-- 访问网络权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- SD卡访问权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    </manifest>

    6.进linux系统查看文件

    adb shell 
    
    ls -l

    cd sdcard
  • 相关阅读:
    架构师时间~白话OAuth2
    vue前端各种问题
    windows命令行导入sql
    正则表达式概述
    XPath语法 在C#中使用XPath示例
    面试宝典
    Repository,UnitOfWork,DbContext(1)
    EF Code First:实体映射,数据迁移,重构(1)
    表单常用的正则表达式
    Lambda表达式
  • 原文地址:https://www.cnblogs.com/zhuawang/p/3649469.html
Copyright © 2011-2022 走看看