URL - FileNotFoundException for image file in Android

前端 未结 6 1742
再見小時候
再見小時候 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:32

    Try the below code. It should work!

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    
    
    public class DownloadManager {
    
        public static void downLoadImage(String imageURL, String destinationFileName) throws IOException {
            URL url = new URL(imageURL);
            InputStream inputStream = url.openStream();
            OutputStream outputStream = new FileOutputStream(destinationFileName);
            byte[] byteData = new byte[2048];
            int length;
            while((length=inputStream.read(byteData))!=-1) {
                outputStream.write(byteData, 0, length);
            }
            inputStream.close();
            outputStream.close();
        }
    
        public static void main(String[] args) throws IOException {
            String imageURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
            String destinationFileName = "C:/Users/sarath_sivan/Desktop/caldophilus.jpg";
            downLoadImage(imageURL, destinationFileName);
        }
    }
    

提交回复
热议问题