InputStream doens不读取URL连接的全部答案

时间:2017-01-09 22:12:54

标签: java android url inputstream

我正在努力反对未完成的文件下载。

例如,我在github上传了一些数据:https://gist.githubusercontent.com/rdanniau/3b7f26bb1101b28400bf24f2f9664828/raw/980d6ff511404bf14d3efc56be3dfb081541991f/LEDirium.hex

并在pasteBin上:http://pastebin.com/raw/FcVfLf5b

我想检索它们并将它们保存到文件" filename"中。 我在互联网上看了很多例子,它必须正常运作。

以下是代码:

    private void download(final URL myUrl){
    new Thread(new Runnable() {
        //InputStream is = null;
        //FileOutputStream fos = null;
        public void run() {
            try {
                URLConnection connection = myURLL.openConnection();
                //HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
                //connection.setRequestMethod("GET");
                connection.setReadTimeout(5000);
                connection.setConnectTimeout(10000);
                connection.connect();

                //is = myUrl.openStream();
                is = connection.getInputStream();
                File file = new File(context.getFilesDir(),fileName);
                file.delete();
                file = new File(context.getFilesDir(),fileName);
                fos = new FileOutputStream(file);
                byte data[] = new byte[1024];
                String str ="";
                int count = 0;
                while ((count = is.read(data)) != -1) {
                    fos.write(data, 0, count);
                }
                is.close();
                fos.close();

            }
            catch (Exception e) {
                downloadedFileCallback.onError(e);
                Log.e("DownloadedFile", "Unable to download : " + e.getMessage() + " cause :" + e.getCause());
                return;
            }
            downloadedFileCallback.onDownloadedFinished();
            readFile(context);
        }
    }).start();
}
public void readFile(Context context){
    // read
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(context.getFilesDir(),fileName)));
        String line;

        while ((line = br.readLine()) != null) {

            Log.v("DL", line);
        }
        br.close();
    }
    catch (Exception e) {
        Log.e("DownloadedFile", "Unable to read : " + e.getMessage() + " cause :" + e.getCause());
    }
    //Log.v("DownloadedFile", text.toString());
}

调用myURL,如

  URL myURL = new URL("http://pastebin.com/raw/FcVfLf5b");

在Log.v中,我可以看到我只下载了一个从不相同的文件的一部分(可能是整个文件,一半,四分之一,我们不知道......)

可能是inputStream连接关闭得太快了。但为什么 ? 最后一个问题,而不是使用Log.v来检查文件是否正确下载。我在哪里可以在手机上找到它?我搜索了许多文件夹,但我从未见过我的文件。

非常感谢任何建议

编辑:这里似乎是InputStream returns -1 before end of file,但没有人回答。

0 个答案:

没有答案