按顺序下载文件

时间:2016-05-17 07:01:20

标签: java android

我的应用程序想要按顺序下载文件,但它显示E / Error:file == null

logcat的

the protected String doInBackground(String... Url) 

我认为问题出在

package shiweichen22gmail.q4;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends AppCompatActivity {
ProgressDialog mProgressDialog;
Button button;
String[] URL = {"https://www.dropbox.com/s/gjq0ivomwti4vmw/1.txt?dl=1&pv=1",
        "https://www.dropbox.com/s/6lolv2ph08wt657/2.txt?dl=1&pv=1",
"https://www.dropbox.com/s/voz5vmnjkzojb14/3.txt?dl=1&pv=1",
"https://www.dropbox.com/s/wv6hika6v2pfakz/4.txt?dl=1&pv=1",
"https://www.dropbox.com/s/7jhtlzfuz2j42d8/5.txt?dl=1&pv=1"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.Button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            new DownloadFile().execute(URL);
        }
    });
}
private class DownloadFile extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setTitle("Downloading");
        mProgressDialog.setMessage("Downloading, Please Wait!");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.show();
    }
    @Override
    protected String doInBackground(String... Url) {
        int count;
        File file = null;
        int i = 0;
        while (i < 5) {
        try {
            URL url = new URL(Url[i]);
            URLConnection connection = url.openConnection();
            connection.connect();
            int fileLength = connection.getContentLength();
            String filepath = Environment.getExternalStorageDirectory()
                    .getPath();
            InputStream input = new BufferedInputStream(url.openStream());
            FileOutputStream output = new FileOutputStream(file);
           file = new File(filepath + "/"
                    + i+".txt");
            byte data[] = new byte[1024];
            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
            publishProgress(i+1);
            i++;
    }
        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        mProgressDialog.setProgress(progress[0]);
    }
}
}

部分  如果我下载一个文件,它的工作原理。但对于多个文件。如何设置文件路径并修复我的代码。非常感谢

Mainactivity.java

class Location < ActiveRecord::Base
  belongs_to :location # i.e. may have a parent location
  has_many :users,  dependent: :restrict_with_error
  validates :name, presence: true, uniqueness: true

  before_save :lowercase_name
  auto_strip_attributes :name, squish: true, nullify: false

  enum status: [
       :invisible, # default
       :major, # a major city
       :minor, # a minor city
       :child, # i.e. it has a parent that should be used instead
   ]
end

1 个答案:

答案 0 :(得分:0)

FileOutputStream output = new FileOutputStream(file);
file = new File(filepath + "/" + i+".txt");

file在第一次迭代中为null,并且由于异常而保持为null。您应该在创建输出流之前初始化file变量。