1

下面是从网络下载图像后写入文件的代码。但不知何故,它只是在写入文件流时卡住了。一点也不例外。它只是停留在while循环上,然后显示强制关闭弹出窗口。它发生在 10 次中的 2 次或 3 次。

private void saveImage(String fullPath) {
  File imgFile = new File(fullPath);
  try {
    if(imgFile.exists()) imgFile.delete();

    URL url = new URL(this.fileURL);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection)connection;
    InputStream in = httpConnection.getInputStream();

    FileOutputStream fos = new FileOutputStream(imgFile);
    int n = 0;
    while((n = in.read()) != -1) {
        fos.write(n);
    }
    fos.flush();
    fos.close();
    in.close();

  }
  catch(IOException e) {
    imgFile.delete();
    Log.d("IOException Thrown", e.toString());
  }
}

当我检查写入的文件时,它在写入到 4576 字节时总是卡住。(原始图像大小超过 150k)有人可以帮助我解决这个问题吗?

4

2 回答 2

2

嗨 Juniano 回答您的第二个问题,是的,您可以使用 while 循环,但您还需要两件事。

  URL url = new URL(this.fileURL);
  URLConnection connection = url.openConnection();
  HttpURLConnection httpConnection = (HttpURLConnection)connection;

  InputStream in = httpConnection.getInputStream();

   BufferedInputStream myBis = new BufferedInputStream(in);

1) 创建一个 ByteArrayBuffer 来存储您的 InputStream

     ByteArrayBuffer myBABuffer = new ByteArrayBuffer(50);
                              int current = 0;
                              while ((current = myBis.read()) != -1) {
                                      myBABuffer.append((byte) current);
                              }    

    FileOutputStream fos = new FileOutputStream(imgFile);

2) 使用存储的字节创建图像。

fos.write(myBABuffer.toByteArray());    
fos.flush();
fos.close();
in.close();

豪尔赫西斯

于 2010-08-13T22:21:21.100 回答
1
private void saveImage(String fullPath) {
  File imgFile = new File(fullPath);
  try {
    if(imgFile.exists()) imgFile.delete();

/**    URL url = new URL(this.fileURL);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection)connection;
    InputStream in = httpConnection.getInputStream();

    FileOutputStream fos = new FileOutputStream(imgFile);
    int n = 0;
    while((n = in.read()) != -1) {
        fos.write(n);
    }
    fos.flush();
    fos.close();
    in.close();***/

 FileOutputStream fos = new FileOutputStream(imgFile);

URL url = new URL(this.fileUR);
Object content = url.getContent();
InputStream in =  (InputStream) content;
Bitmap bitmap = BitmapFactory.decodeStream(in);
bitmap.compress(CompressFormat.JPEG,80, fos);
fos.flush();
fos.close();
in.close();


  }
  catch(IOException e) {
    imgFile.delete();
    Log.d("IOException Thrown", e.toString());
  }
}
于 2010-08-13T19:08:23.380 回答