Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    (1)文件的目录

   

    (2)各文件的代码:

FileService.java也就是操作sdcard的工具类:

package com.example.data_storage_sdcard.file;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import android.os.Environment;/** * sdcard的存在于上下文无关 *  * @author piaodangdehun *  */public class FileService {	/*	 * 存放在sdcard的根目录	 */	public boolean saveFileToSdcardRoot(String fileName, byte[] data) {		boolean flag = false;		/*		 * 先判断sdcard的状态,是否存在		 */		String state = Environment.getExternalStorageState();		FileOutputStream utputStream = null;		File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径		/*		 * 表示sdcard挂载在手机上,并且可以读写		 */		if (state.equals(Environment.MEDIA_MOUNTED)) {			File file = new File(rootFile, fileName);			try {				utputStream = new FileOutputStream(file);				try {					outputStream.write(data, 0, data.length);					flag = true;				} catch (IOException e) {					e.printStackTrace();				}			} catch (FileNotFoundException e) {				e.printStackTrace();			} finally {				if (outputStream != null) {					try {						outputStream.close();					} catch (IOException e) {						e.printStackTrace();					}				}			}		}		return flag;	}	/*	 * 存放在sdcard下自定义的目录	 */	public boolean saveFileToSdcardDir(String fileName, byte[] data) {		boolean flag = false;		/*		 * 先判断sdcard的状态,是否存在		 */		String state = Environment.getExternalStorageState();		FileOutputStream utputStream = null;		File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径		/*		 * 表示sdcard挂载在手机上,并且可以读写		 */		if (state.equals(Environment.MEDIA_MOUNTED)) {			File file = new File(rootFile.getAbsoluteFile() + /txt);			if (!file.exists()) {				file.mkdirs();			}			try {				utputStream = new FileOutputStream(new File(file, fileName));				try {					outputStream.write(data, 0, data.length);					flag = true;				} catch (IOException e) {					e.printStackTrace();				}			} catch (FileNotFoundException e) {				e.printStackTrace();			} finally {				if (outputStream != null) {					try {						outputStream.close();					} catch (IOException e) {						e.printStackTrace();					}				}			}		}		return flag;	}	/*	 * 用于读取sdcard的数据	 */	public String readContextFromSdcard(String fileName) {		String state = Environment.getExternalStorageState();		File rooFile = Environment.getExternalStorageDirectory(); // 获得sdcard的目录		FileInputStream inputStream = null;// 用于度取数据的流		ByteArrayOutputStream utputStream = new ByteArrayOutputStream(); // 用于存放独处的数据		if (state.equals(Environment.MEDIA_MOUNTED)) {			File file = new File(rooFile.getAbsoluteFile() + /txt/);// 在sdcard目录下创建一个txt目录			File file2 = new File(file, fileName);			int len = 0;			byte[] data = new byte[1024];			if (file2.exists()) {				try {					inputStream = new FileInputStream(file2);					try {						while ((len = inputStream.read(data)) != -1) {							outputStream.write(data, 0, data.length);						}					} catch (IOException e) {						e.printStackTrace();					}					return new String(outputStream.toByteArray());				} catch (FileNotFoundException e) {					// TODO Auto-generated catch block					e.printStackTrace();				} finally {					if (outputStream != null) {						try {							outputStream.close();						} catch (IOException e) {							e.printStackTrace();						}					}				}			}		}		return null;	}	/**	 * 对文件进行分类的保存到固定的文件中去	 * 	 * @param fileName	 * @param data	 */	public void saveFileToSdcardBySuff(String fileName, byte[] data) {		// File file = Environment.getExternalStoragePublicDirectory();		// 保存文件的目录		File file = null;		if (Environment.getExternalStorageState().equals(				Environment.MEDIA_MOUNTED)) {			/*			 * 将不同的文件放入到不同的类别中			 */			if (fileName.endsWith(.mp3)) {				file = Environment						.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);			} else if (fileName.endsWith(.jpg) || fileName.endsWith(.png)					|| fileName.endsWith(.gif)) {				file = Environment						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);			} else if (fileName.endsWith(.mp4) || fileName.endsWith(.avi)					|| fileName.endsWith(.3gp)) {				file = Environment						.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);			} else {				file = Environment						.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);			}			FileOutputStream utputStream = null;			try {				utputStream = new FileOutputStream(new File(file, fileName));				try {					outputStream.write(data, 0, data.length);				} catch (IOException e) {					e.printStackTrace();				}			} catch (FileNotFoundException e) {				e.printStackTrace();			} finally {				if (outputStream != null) {					try {						outputStream.close();					} catch (IOException e) {						e.printStackTrace();					}				}			}		}	}	/*	 * 删除一个文件	 */	public boolean deleteFileFromSdcard(String folder, String fileName) {		boolean flag = false;		File file = Environment.getExternalStorageDirectory();		if (Environment.getExternalStorageState().equals(				Environment.MEDIA_MOUNTED)) {			File exitFile = new File(file.getAbsoluteFile() + / + folder);			if (exitFile.exists()) {				exitFile.delete();			}		}		return flag;	}}

    HttpUtils.java访问网络的

package com.example.data_storage_sdcard.http;import java.io.IOException;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;public class HttpUtils {	/*	 * 	 */	public static byte[] getImage(String path) {		byte[] data = null;		HttpClient httpClient = new DefaultHttpClient();		HttpPost httpPost = new HttpPost(path);		try {			HttpResponse response = httpClient.execute(httpPost);			if (response.getStatusLine().getStatusCode() == 200) {				data = EntityUtils.toByteArray(response.getEntity());			}		} catch (ClientProtocolException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		} finally {			httpClient.getConnectionManager().shutdown();		}		return data;	}}

    ImageCache.java将文件放到cache中的:

package com.example.data_storage_sdcard.img;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import android.os.Environment;public class ImageCache {	public static  String saveImageCache(String fileName, byte[] data) {		File file = Environment.getExternalStorageDirectory(); // 根目录		FileOutputStream utputStream = null;		if (Environment.getExternalStorageState().equals(				Environment.MEDIA_MOUNTED)) {			try {				utputStream = new FileOutputStream(new File(file, fileName));				outputStream.write(data, 0, data.length);				return file.getAbsolutePath() + / + fileName;			} catch (Exception e) {				e.printStackTrace();			} finally {				if (outputStream != null) {					try {						outputStream.close();					} catch (IOException e) {						e.printStackTrace();					}				}			}		}		return null;	}}

    MainActivity.java

package com.example.data_storage_sdcard;import android.app.Activity;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;import com.example.data_storage_sdcard.http.HttpUtils;import com.example.data_storage_sdcard.img.ImageCache;public class MainActivity extends Activity {	private Button button;	private ImageView imageView;	private ProgressDialog progressDialog;	private String imageName;	private final String pathString = http://www.baidu.com/img/bd_logo1.png;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		button = (Button) this.findViewById(R.id.button1);		imageView = (ImageView) this.findViewById(R.id.imageView1);		progressDialog = new ProgressDialog(this);		progressDialog.setTitle(下载提示);		progressDialog.setMessage(load...);		button.setOnClickListener(new OnClickListener() {			@Override			public void onClick(View v) {				new MyTask().execute(pathString);			}		});	}	class MyTask extends AsyncTask<string,>{		@Override		protected void onPreExecute() {			super.onPreExecute();			progressDialog.show();		}		@Override		protected byte[] doInBackground(String... params) {			String name = params[0];			imageName = name					.substring(name.lastIndexOf(/) + 1, name.length());			return HttpUtils.getImage(params[0]);		}		@Override		protected void onProgressUpdate(Void... values) {			super.onProgressUpdate(values);		}		@Override		protected void onPostExecute(byte[] result) {			super.onPostExecute(result);			if (result != null) {				Bitmap bm = BitmapFactory.decodeByteArray(result, 0,						result.length);				imageView.setImageBitmap(bm);				ImageCache.saveImageCache(, result);			} else {				imageView.setImageResource(R.drawable.ic_launcher);			}			progressDialog.dismiss();		}	}	@Override	public boolean onCreateOptionsMenu(Menu menu) {		// Inflate the menu; this adds items to the action bar if it is present.		getMenuInflater().inflate(R.menu.main, menu);		return true;	}}</string,>

    测试类:

package com.example.data_storage_sdcard;import java.io.FileWriter;import com.example.data_storage_sdcard.file.FileService;import android.nfc.Tag;import android.test.AndroidTestCase;import android.util.Log;public class MyTest extends AndroidTestCase {	public void saveFileToSdcardTest() {		FileService fileService = new FileService();		fileService.saveFileToSdcardRoot(aa.txt,				jkhdsfjkhdskjfhdsjf.getBytes());	}	public void saveFileToSdcardDir() {		FileService fileService = new FileService();		fileService.saveFileToSdcardRoot(aa.txt,				jkhdsfjkhdskjfhdsjf.getBytes());	}	public void readContextFromSdcardTest() {		FileService fileService = new FileService();		String msg = fileService.readContextFromSdcard(aa.txt);		System.err.println(--> + msg);	}	public void saveFileToSdcardBySuffTest() {		FileService fileService = new FileService();		fileService.saveFileToSdcardBySuff(aa.avi,				asdfkajsgdhagsdfhdgsf.getBytes());	}	public void delFile() {		FileService fileService = new FileService();		boolean flag = fileService.deleteFileFromSdcard(txt, aa.txt);	}}

    需要在请单位按中加入访问网络的权限、操作sdcard的权限、测试的权限

<manifest android:versioncode="1" android:versionname="1.0" package="com.example.data_storage_sdcard" xmlns:android="http://schemas.android.com/apk/res/android"><uses-sdk android:minsdkversion="8" android:targetsdkversion="18"><instrumentation android:name="android.test.InstrumentationTestRunner" android:targetpackage="com.example.data_storage_sdcard"></instrumentation><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"><uses-permission android:name="android.permission.INTERNET"><uses-library android:name="android.test.runner"><intent-filter><category android:name="android.intent.category.LAUNCHER"></category></intent-filter><uses-library></uses-library></uses-library></uses-permission></uses-permission></uses-sdk></manifest>

最新文章