将文件保存到android的内部存储器中

将文件保存到android的内部存储器中

本文介绍了将文件保存到android的内部存储器中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在借助Web服务提供的URL从服务器下载文件.我对每种版本的设备都成功,但是在OS 4.1设备中却出现异常.我正在使用以下代码:

I am downloading a file from server with help of a URL provided through web service.I am successful for every version of devices but getting exception in OS 4.1 devices. I am using below code:

public static Boolean DownloadFile(String fileURL, File directory) {
                try {

                        FileOutputStream f = new FileOutputStream(directory);
                        URL u = new URL(fileURL);
                        HttpURLConnection c = (HttpURLConnection) u.openConnection();
                        c.setRequestMethod("GET");
                        c.setDoOutput(true);
                        c.connect();

                        InputStream in = c.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len1 = 0;
                        while ((len1 = in.read(buffer)) > 0) {
                                f.write(buffer, 0, len1);
                        }
                        f.close();
                        return true;
                } catch (Exception e) {
                        e.printStackTrace();
                        return false;
                }
        }

我在行 c.getInputStream(); 上获得了java.io.FileNotFoundException请建议我解决这个问题.

I am getting java.io.FileNotFoundException at line c.getInputStream();please suggestion me to solve this problem.

我打算使用内部存储器,但是由于用户无法访问内部存储器.

I am planning to use the internal memory but as user cant access the internal memory.

推荐答案

尝试以下代码:请注意,CONTEXT创建文件可以是Activity/ApplicationContext/etc

Try this code:Notice that CONTEXT creating the file could be an Activity/ApplicationContext/etc

public boolean downloadFile(final String path) {
    try {
        URL url = new URL(path);

        URLConnection ucon = url.openConnection();
        ucon.setReadTimeout(5000);
        ucon.setConnectTimeout(10000);

        InputStream is = ucon.getInputStream();
        BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);

        File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/yourfile.png");

        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();

        FileOutputStream outStream = new FileOutputStream(file);
        byte[] buff = new byte[5 * 1024];

        int len;
        while ((len = inStream.read(buff)) != -1) {
            outStream.write(buff, 0, len);
        }

        outStream.flush();
        outStream.close();
        inStream.close();

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

这篇关于将文件保存到android的内部存储器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:26