1

我试图使用以下代码获取下载进度:

Java程序代码:

URLConnection conn = null;
URL url = null;
try {
    url = new URL("http://stackoverflow.com");
    conn = url.openConnection();
    conn.connect();
    InputStream in = new BufferedInputStream(url.openStream());
    int fileSize = conn.getContentLength();
    System.out.println("File size " + fileSize);
    int count;
    int i=0;
    while ((count = in.read()) != -1) {
        i++;
        if(i%50000==0){//Prints the decimal percentage every 50000 bytes
            System.out.println(((double)i)/((double)fileSize));
        }
    }
    in.close();
    System.out.println("Read " + i + " bytes of a possible " + fileSize);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

当我在 java 应用程序的 Main 中尝试相同的代码时,我得到(几乎)正确的输出:

读取可能的 191174 的 191202 字节

现在,如果我尝试将其集成到android 应用程序中,在sAsyncTask中使用完全相同的代码并调用in (如下所示),我会得到结果AsyncTaskdoInBackground()AsyncTaskonCreate()

读取可能的 16983 的 156846 字节

那么不仅android中的文件大小错误,而且读取的字节数也不同?我下载相同的文件并得到完全不同的结果。我已经运行了多次并且都给出了大致相同的结果(stackoverflow 的大小确实略有不同,但只有大约 +/-5000 字节)。有人可以解释一下并帮我解决吗?

安卓代码:

public class MainActivity extends Activity {

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

    private class LoadData extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... params) {
            URLConnection conn = null;
            URL url = null;
            try {
                url = new URL("http://stackoverflow.com");
                conn = url.openConnection();
                conn.connect();
                InputStream in = new BufferedInputStream(url.openStream());
                int fileSize = conn.getContentLength();
                System.out.println("File size " + fileSize);
                int count;
                int i=0;
                while ((count = in.read()) != -1) {
                    i++;
                    if(i%50000==0){//Prints the decimal percentage every 50000 bytes
                        System.out.println(((double)i)/((double)fileSize));
                    }
                }
                in.close();
                System.out.println("Read " + i + " bytes of a possible " + fileSize);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
4

0 回答 0