save file to internal memory in android?

前端 未结 2 1532
予麋鹿
予麋鹿 2021-01-23 18:17

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

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-23 19:11

    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;
    }
    

提交回复
热议问题