Android之訪問下載文件

 

 

1.SD卡操做類 FileUtils.javahtml

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.下載類HttpDownloaderjava

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.下載文件Activitylinux

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.設置權限android

<?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" >shell

<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" />app

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

</application>ide


<!-- 訪問網絡權限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- SD卡訪問權限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>函數

 

6.進linux系統查看文件ui

adb shell 

ls -lcd sdcard
相關文章
相關標籤/搜索