android - java怎么把一个网址下载下来呢,并且指定保存位置呢
巴扎黑
巴扎黑 2017-04-17 17:13:18
0
1
390

以下代码,网址才不过是2K的歌词文件,然后制定保存目录,下载下来有200多K,并且打不开.....这是怎么回事?

怎么下载网址:http://s.geci.me/lrc/365/36503/3650301.lrc

并且能制定保存在缓存上面呢?

package china.testthree;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private String path = "http://s.geci.me/lrc/365/36503/3650301.lrc";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownTash().execute(path);
    }

    class DownTash extends AsyncTask<String, Void, File> {


        @Override
        protected File doInBackground(String... strings) {

            String url = strings[0];
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            HttpURLConnection conn = null;
            try {

                URL url1 = new URL(url);
                conn = (HttpURLConnection) url1.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(3000);

                File file = new File(getApplicationContext().getExternalCacheDir().getAbsolutePath(), "111.lrc");
                Log.i("ddd", file.getPath());

                bis = new BufferedInputStream(conn.getInputStream());

                bos = new BufferedOutputStream(new FileOutputStream(file));

                byte[] bytes = new byte[1024];

                int len;

                while ((len = bis.read()) != -1) {

                    bos.write(bytes, 0, len);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                try {
                    bis.close();
                    bos.close();
                    conn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            return null;
        }
    }
}
巴扎黑
巴扎黑

全部回覆(1)
伊谢尔伦

應該是byte[] bytes = new byte[1024];不能用fileOutputStream

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板