Android - 如何从特定站点下载xls文件

时间:2014-11-04 12:57:41

标签: java android

在我的应用程序中,我正在尝试从站点下载xls文件,但我有一个错误,例如不幸的是,当我点击下载按钮时,MyApp已停止。我不能理解为什么我有这个问题。

MyActivity.java

        package com.example.mine.myapp;

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, 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);
    }

    public void button1_Click(View view) throws IOException {
        downloadFile();

    }

    public void downloadFile() throws IOException {
        URL url = new URL("https://www.myste.com/myxlsfile.xls");

//create the new connection

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//set up some things on the connection

        urlConnection.setRequestMethod("GET");

        urlConnection.setDoOutput(true);

//and connect!

        urlConnection.connect();

//set the path where we want to save the file

//in this case, going to save it on the root directory of the

//sd card.

        File SDCardRoot = new File("/storage/"+"sdcard1/");

//create a new file, specifying the path, and the filename

//which we want to save the file as.

        File file = new File(SDCardRoot,"name.xls");

//this will be used to write the downloaded data into the file we created

        FileOutputStream fileOutput = new FileOutputStream(file);

//this will be used in reading the data from the internet

        InputStream inputStream = urlConnection.getInputStream();

//this is the total size of the file

        int totalSize = urlConnection.getContentLength();

//variable to store total downloaded bytes

        int downloadedSize = 0;

//create a buffer...

        byte[] buffer = new byte[1024];

        int bufferLength = 0; //used to store a temporary size of the buffer

//now, read through the input buffer and write the contents to the file

        while ( (bufferLength = inputStream.read(buffer)) > 0 )

        {

//add the data in the buffer to the file in the file output stream (the file on the sd card

            fileOutput.write(buffer, 0, bufferLength);

//add up the size so we know how much is downloaded

            downloadedSize += bufferLength;

            int progress=(int)(downloadedSize*100/totalSize);

//this is where you would do something to report the prgress, like this maybe

//updateProgress(downloadedSize, totalSize);

        }

//close the output stream when done

        fileOutput.close();
    }
}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MyActivity"
        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>

Activity_my.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Download"
    android:id="@+id/button1"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:onClick="button1_Click"/>

1 个答案:

答案 0 :(得分:0)

我认为您需要打开一个线程或异步任务来从服务器下载文件。 在这个线程中,使用android.os.Handler将任何进度/结果通知给主ui线程。