最近开始做一个android的一个小项目的开发,其中涉及到图片的本地缓存,调用写好的工具类执行,发现当工具类里边写入的时候用BufferedOutputStream和FileOutPutStream的结果不一样,当用Buffered的时候,写出来的文件会比源文件大,并且,当用Buffered的方法把网上的图片文件Down到本地的时候,图片会发生异常的错误,本人是一个新手阿,表示非常的费解,百度过也google过,没有找到解法,希望各位能帮帮忙
现边首先放上布局文件
- XML code
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/Download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /></LinearLayout>
接下来是Main activity
- Java code
package com.Kiro.DownloadTool;import java.io.InputStream;import java.net.URL;import org.apache.http.impl.conn.Wire;import com.Kiro.FileTool.Read;import com.Kiro.FileTool.Write;import com.Kiro.Tool.R;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;public class Main extends Activity implements OnClickListener { private ImageView image = null; private String sd = null; protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.download); sd = Environment.getExternalStorageDirectory().toString() + "/"; ((Button) findViewById(R.id.Download)).setOnClickListener(this); image = (ImageView) findViewById(R.id.imageView1); } @Override public void onClick(View v) { // TODO Auto-generated method stub InputStream input = new Download( "http://www.hmecw.com/file/upload/201109/05/09-42-46-51-45140.jpg.middle.jpg") .getInputStream(); new Write(input, sd + "a.jpg", 1024).process(); try { input.close(); } catch (Exception e) { // TODO: handle exception } }}
接下来是download java文件
- Java code
package com.Kiro.DownloadTool;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import org.apache.http.HttpConnection;public class Download { private String Address; public Download(String address) { super(); Address = address; }// url = new URL(urlStr);// 创建一个URL对象 // HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 创建一个Http连接// InputStream inputStream = urlConn.getInputStream();//得到输入流 public InputStream getInputStream() { InputStream ret = null; try { URL url = new URL(Address); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); ret=conn.getInputStream(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return ret; } }
然后是最后一个代码断,Write文件
- Java code