0

我有一个示例代码可以从 Web 及其 Swing 应用程序下载一些数据(pdf、gif 和 mp3)。它在 Windows 7 中完美运行,但在 Windows xp 中无法运行。

我的代码是

 public static Float downloadFile(String targetUrl,File filePath)
        {
            try
            {

                Integer count=0;
                URL url = new URL(targetUrl);
                HttpURLConnection connection=(HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(true);
                connection.setConnectTimeout(10000);
                connection.connect();

                int lenghtOfFile = connection.getContentLength();
                Thread.sleep(100);
                InputStream input = new BufferedInputStream(url.openStream());
                Thread.sleep(100);
                OutputStream output = new FileOutputStream(filePath);
                byte data[] = new byte[input.available()];
                long total = 0;
                while ((count = input.read(data)) != -1)
                {
                    total += count;
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return 2.5f;
            }  
    }

它通过将代码设置为0进入无限while循环

4

1 回答 1

0

问:初始化缓冲区时,什么是“input.available()”?如果那一刻恰好是“0”,你会很难过。

一种解决方案是使用固定长度的缓冲区(例如 8192)。

于 2013-02-28T05:57:08.557 回答