在 Android 中下载文件时程序冻结

发布于 2024-11-19 12:56:57 字数 1744 浏览 1 评论 0原文

我在以下代码中收到 MalformedURLException,但我不知道是什么原因导致的。

public void down(String url)
    {     try {
        URL url1 = new URL(url);


        HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();   
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, specifying the path, and the filename
        //which we want to save the file as.
        File file = new File(SDCardRoot,"somefile.ext");


        FileOutputStream fileOutput = new FileOutputStream(file);

        InputStream inputStream = urlConnection.getInputStream();

        int 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);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //report progress


        }

        fileOutput.close();


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

    }
    }
}

它说未知协议。 在阅读部分出现之前,连接完全正常, 在此之前,代码甚至可以打印正确大小的文件。 另外,我尝试下载的文件的网址如下 http://download12.aomethin.com/blaa-blaa 如果我尝试添加 www,请求就会开始重定向。 虽然我认为这可能有点小菜一碟,但我也想知道如何获取该文件的名称并使用该名称而不是我选择的名称保存文件。

编辑:程序现在正在运行,我只需要知道如何获得正确的文件名。并将其设为后台进程。

I am getting MalformedURLexception in the following code, and i have no idea, whats causing it.

public void down(String url)
    {     try {
        URL url1 = new URL(url);


        HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();   
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, specifying the path, and the filename
        //which we want to save the file as.
        File file = new File(SDCardRoot,"somefile.ext");


        FileOutputStream fileOutput = new FileOutputStream(file);

        InputStream inputStream = urlConnection.getInputStream();

        int 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);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //report progress


        }

        fileOutput.close();


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

    }
    }
}

It says unknown protocol.
The connection is totally fine unti the reading part comes up,
before that the code is even printing right size of the file.
Also the file i am trying to download has a url like
http://download12.aomethin.com/blaa-blaa
If i try to add www, the request starts redirecting.
Although i think this might be a noobish but I also want to know how to get the name of this file and save file with that name instead of the one i choose.

Edit: the program is working now i just need to know how do i get the right name of the file. And make this a background process.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最舍不得你 2024-11-26 12:56:57

在主线程上下载不是一个好的做法;你应该在一个新线程上实现它;因为在下载时,主线程正忙于下载文件。如果等待时间超过预期,系统将生成“未响应”错误。

为此,您可以使用“TaskAsync”或“IntentService" 甚至创建一个新线程。不过,我建议 [TaskAsync],因为它很容易实现。

这是自己设置文件名的好习惯:

public void downloadClicked() {
    InputStream in = null;
    FileOutputStream f = null;      
    try {
        String path ="ftp://administrator:[email protected]:21/MyShedule.zip";
        String targetFileName = "MyShedule.zip";

        URL u = new URL(path);
        URLConnection c =  u.openConnection();         

        c.setDoOutput(true);
        c.connect();
        String string = Environment.getExternalStorageDirectory().getPath().toString();

        in = c.getInputStream();

        f = new FileOutputStream(new File(string +"/kidsLibrary/"+ targetFileName));

        IOUtils.copy(in, f);

        } catch (MalformedURLException e) {
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();            
        } catch (ProtocolException e) {         
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();
        } catch (FileNotFoundException e) {        
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();
        } catch (IOException e) {           
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();
    } finally {
          IOUtils.closeQuietly(in);
          IOUtils.closeQuietly(f);
        }   
}

downloading on the main thread is not a good practice; you should implement it on a new thread; because while downloading, the main thread is busy for downloading the file. If the waiting time be more than expected the system will generate "Not responding" error.

In order to do that you can use "TaskAsync" or "IntentService" or even making a new thread. though, I suggest [TaskAsync] as it is easy to implement.

here is a good practice to set the file name yourself:

public void downloadClicked() {
    InputStream in = null;
    FileOutputStream f = null;      
    try {
        String path ="ftp://administrator:[email protected]:21/MyShedule.zip";
        String targetFileName = "MyShedule.zip";

        URL u = new URL(path);
        URLConnection c =  u.openConnection();         

        c.setDoOutput(true);
        c.connect();
        String string = Environment.getExternalStorageDirectory().getPath().toString();

        in = c.getInputStream();

        f = new FileOutputStream(new File(string +"/kidsLibrary/"+ targetFileName));

        IOUtils.copy(in, f);

        } catch (MalformedURLException e) {
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();            
        } catch (ProtocolException e) {         
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();
        } catch (FileNotFoundException e) {        
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();
        } catch (IOException e) {           
            Toast.makeText(KidsLibrary.this, e.toString(), Toast.LENGTH_LONG)
            .show();
    } finally {
          IOUtils.closeQuietly(in);
          IOUtils.closeQuietly(f);
        }   
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文