代码之家  ›  专栏  ›  技术社区  ›  juniano

android应用程序写问题

  •  1
  • juniano  · 技术社区  · 16 年前

    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) 在这个问题上有人能帮我吗?

    2 回复  |  直到 16 年前
        1
  •  1
  •   Jorgesys    16 年前
    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());
      }
    }
    
        2
  •  2
  •   Jorgesys    16 年前

    嗨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来存储输入流

         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();
    

    乔吉斯