Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这就是从HTTP下载文件的方式吗?_Java_Android_Http_Download_Buffer - Fatal编程技术网

Java 这就是从HTTP下载文件的方式吗?

Java 这就是从HTTP下载文件的方式吗?,java,android,http,download,buffer,Java,Android,Http,Download,Buffer,在阅读了internet上的教程后,我想到了从HTTP下载声音文件的功能: try { URL url = new URL(filePath); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET");

在阅读了internet上的教程后,我想到了从HTTP下载声音文件的功能:

        try {
            URL url = new URL(filePath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File directory = new File(storage.getAbsolutePath());
            directory.mkdirs();

            file = new File(directory, fileName + ".mp3");

            FileOutputStream fileOutput = new FileOutputStream(file);

            InputStream inputStream = urlConnection.getInputStream();

             totalSize = urlConnection.getContentLength();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer


            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                Log.i("download:", downloadedSize + "/" + totalSize);
            }

            fileOutput.close();
        } catch (IOException e) {
            e.printStackTrace(); 
        }
它在我的设备和各种模拟器上都能正常工作,但一些用户抱怨无法下载该文件。 有什么我遗漏的吗?为什么它在我的设备上工作,但在其他几个设备上出现故障?
如果有人能检查一下并告诉我这是否正确,我会很高兴的。

urlConnection.setDoOutput(true)


这是不正确的。您没有向服务器发送内容。

我认为这是因为其他人的手机系统版本不同,API也不同。您需要适应较新版本的移动电话系统

directory.mkdirs()错误。如果(!directory.exists())如果(!directory.mkdirs())返回,则应该是
开始下载之前,请先查看目录。如果目录不存在,请不要开始下载。您现在如何知道无法创建目录?
catch(IOException e)
捕获异常是件好事。但是现在。。。如果有例外。。。如何将异常消息
e.getMessage()
发送给用户?好的,谢谢,urlConnection.setRequestMethod(“GET”);如果您删除“setDoOutput()”,那么?也应该是默认值。