URL - FileNotFoundException for image file in Android

前端 未结 6 1731
再見小時候
再見小時候 2020-12-17 04:04

I\'m trying to get a image from particular URL but it throwsFileNotFoundException. If I try to open the url from my browser, i can see the images. Please help.

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 04:26

    Try this:

      BufferedInputStream inputStream = null;
      OutputStream out = null;
    
      String fileName = null;
      String path = null;
      File savedFile = null;
    
      try
      {
          // Replace your URL here.
          URL fileURL = new URL("http://enter.your.url.here");
          URLConnection connection = fileURL.openConnection();
          connection.connect();
    
          inputStream = new java.io.BufferedInputStream(connection.getInputStream());
    
          // Replace your save path here.
          File fileDir = new File("path/to/save");
          fileDir.mkdirs();
          savedFile = new File("path/to/save", fileName);
          out = new FileOutputStream(savedFile);
    
          byte buf[] = new byte[1024];
          int len;
    
          long total = 0;
    
          while ((len = inputStream.read(buf)) != -1)
          {
            total += len;
            out.write(buf, 0, len);
          }
    
          out.close();
          inputStream.close();
      }
      catch (Exception)
      {
    
      }
    

提交回复
热议问题