save file to internal memory in android?

前端 未结 2 1500
予麋鹿
予麋鹿 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:10

    try this code:

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir, fname);
    
    if (file.exists()) file.delete();
    
    try {
      FileOutputStream out = new FileOutputStream(file);
      finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    

    and add in manifest:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题