在Android应用程序上写问题

时间:2010-08-13 18:44:17

标签: android fileoutputstream

以下是从Web下载图像后写入文件的代码。但不知何故,它只是在写入文件流时卡住了。完全没有例外。它只是在循环时保持打开然后显示强制关闭弹出窗口。它发生在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());
  }
}

当我检查写入的文件时,它在写入4576byte时总是卡住。 (原始图像尺寸超过150k) 有没有人可以帮我解决这个问题?

2 个答案:

答案 0 :(得分: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();

Jorgesys

答案 1 :(得分: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());
  }
}