`
QCheng5453
  • 浏览: 15886 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

Android笔记——Day4 *Android对SD卡的操作

阅读更多

前两天去苏州玩了,今天终于又可以学Android写博客了--#

 

Android对SD卡的操作

 

··Android对SD卡的操作总的来说简单的分为读文件和写文件。

··一般分为创建文件,打开文件,写入内容,读出内容,插入内容等操作。

··在创建文件时,首先要检查SD卡的状态,是可读可写,还是只读,还是不存在。

··具体的操作,我写了一个助手类,封装了一些函数,里面的注释应该写的比较清楚了。

 

package my.seu;
/*
 * 写了一个SDCardFile类,封装了许多函数功能,具体功能见每个类前面的注释
 * 有些地方可能还不够完善,调用函数时最好能加上try-catch结构。
 * 
 * 一个类对象代表一个SD卡中的文件。
 */


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.os.Environment;

public class SDCardFile {

	private Context context;
	/** SD卡是否存在 **/
	private boolean hasSD = false;
	/** SD卡的路径 **/
	private String SDPATH;
//	/** 当前程序包的路径 **/
//	private String FILESPATH;
	private String wholePath;
	private String nameOfFile;
	private FileInputStream fileinputstream = null;
	private BufferedReader br = null;       //将FileInputStream和BufferedReader都设为私有成员,方便之后输出
	
	/*
	 * 下面注释掉的是网上找过来的为了获取程序包位置的构造函数,没用就注释掉了
	 */
//	public SDCardFile(Context context) {
//		this.context = context;
//		hasSD = Environment.getExternalStorageState().equals(
//				android.os.Environment.MEDIA_MOUNTED);
//		SDPATH = Environment.getExternalStorageDirectory().getPath();
//		FILESPATH = this.context.getFilesDir().getPath();
//	}
	
	
	
	/*
	 * 用文件夹名和文件名初始化SDCardFile对象,创建并将文件流赋给私有成员
	 */
	public SDCardFile(String packageName, String fileName){
		hasSD = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);			//只检验是否可读且可写
		if(hasSD){
			try{
				SDPATH = Environment.getExternalStorageDirectory().getAbsolutePath();//这里最好是获取绝对路径
	            File destDir = new File(SDPATH + "/"+packageName);
	            if (!destDir.exists()) destDir.mkdir();                 //File类可以是文件或文件夹,如果该文件夹不存在,则创建该文件夹
	            wholePath = (SDPATH + "/"+packageName+ "/" + fileName).trim(); //这句重要,防止绝对路径中存在空格,导致文件路径寻找不到,报错。
				File file = new File(wholePath);
				if (!file.exists()) {
					try{
						file.createNewFile();            //如果文件不存在,则创建该文件
					}catch (Exception e) {
						 e.printStackTrace();
					}
				}
				nameOfFile = fileName;				
			}catch (Exception e) {
				System.out.println(e);
				System.out.println("SDCard is not valid");
			
			}finally{
				try{
					fileinputstream = new FileInputStream(wholePath);
					br = new BufferedReader(new InputStreamReader(fileinputstream));//需要先将字节流转为字符流,因为BufferedReader是字符流
				}catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
			}
		}
		else{
			System.out.println("SCCard not ex");
		}
	}
	
	/*
	 * 只用文件名创建对象,默认位置为SD卡根目录,创建并将文件流赋给私有成员
	 */
	public SDCardFile(String fileName){
		hasSD = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if(hasSD){
			try{
				SDPATH = Environment.getExternalStorageDirectory().getAbsolutePath();
	            wholePath = (SDPATH + "/" + fileName).trim();
				File file = new File(wholePath);
				if (!file.exists()) {
					try{
						file.createNewFile();
					}catch (Exception e) {
						 e.printStackTrace();
						// TODO: handle exception
					}
				}
				nameOfFile = fileName;				
			}catch (Exception e) {
				System.out.println(e);
				System.out.println("SDCard is not valid");
			
			}finally{
				try{
					fileinputstream = new FileInputStream(wholePath);
					br = new BufferedReader(new InputStreamReader(fileinputstream));//需要先将字节流转为字符流,因为BufferedReader是字符流
				}catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
			}
		}else{
			System.out.println("SCCard not ex");
		}
	}

	/*
	 * 获取总路径
	 */
	public String getWholePath(){
		return wholePath;
	}
	/*
	 * 获取SD卡状态
	 */
	public boolean getSDCardState(){
		return hasSD;
	}
	/*
	 * 获取文件名
	 */
	public String getFileName(){
		return nameOfFile;
	}
	

	
	/*
	 *返回一行字符串
	 */
	public String getLine(){
        String line = null;  
        try{              
            line = br.readLine();
        }catch (Exception e) {  
        	System.out.println("Cannot getline");
        }finally{
        	return line;
        }       
	}
	
	/*
	 * 读取整个文件内容
	 */
	public String readSDFile() {
		StringBuffer sb = new StringBuffer();
		File file = new File(wholePath);
		try {
			FileInputStream fis = new FileInputStream(file);
			int c;
			while ((c = fis.read()) != -1) {
				sb.append((char) c);
			}
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	
	/*
	 * 重写文件
	 * 这里面很多步骤省着写了,其实不是好的编程习惯...--#
	 */
	public boolean write(String content){
		try{
	        FileOutputStream outputStream = new FileOutputStream(wholePath);
	        outputStream.write(content.getBytes());
	        outputStream.close();
	        return true;
		}catch (Exception e) {
			return false;
			// TODO: handle exception
		}
	}
	
	
	/*
	 * 重载write函数,以InputStream对象为参数
	 */
	public boolean write(InputStream is){
		this.write("");
		String temp;
		try{
			FileOutputStream outputStream = new FileOutputStream(wholePath);
			byte[] b = new byte[1024];
			while(true){
				int len = is.read(b, 0, b.length);
				if(len == -1){
					break;
				}
				outputStream.write(b,0,len);
			}		
			outputStream.close();
			return true;
		}catch (Exception e) {
			return false;
			// TODO: handle exception
		}
	}
	
	
	/*
	 * 在文件末尾添加数据
	 */
	public boolean append(String content){
		try{
			FileWriter fw = new FileWriter(wholePath,true); //将第二个参数设置为true,写入数据时就是在文件末尾添加
			fw.write(content);
			fw.close();
			return true;
		}catch (Exception e) {
			return false;
			// TODO: handle exception
		}
	}

	/*
	 * 删除文件
	 */
	public boolean deleteSDFile() {
		File file = new File(wholePath);
		if (file == null || !file.exists() || file.isDirectory())
			return false;
		return file.delete();
	}

	/*
	 * 在文件末尾添加字节流
	 * 
	 *未写,感觉无必要,因为大部分需要在末尾添加的文件都是字符文件,像mp3,flv等完全没必要在文件末尾添加字节流
	 */
	
	/*
	 * 返回SD卡总的容量,单位是MB,(网上搜罗)--#
	 */
	public static long getTotalStorage() {
		  
		          // 取得SDCard当前的状态
		 String sDcString = android.os.Environment.getExternalStorageState();
		  
		          if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {
		  
		              // 取得sdcard文件路径
		              File pathFile = android.os.Environment
		                     .getExternalStorageDirectory();
		 
		             android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());
		 
		             // 获取SDCard上BLOCK总数
		             long nTotalBlocks = statfs.getBlockCount();
		 
		             // 获取SDCard上每个block的SIZE
		             long nBlocSize = statfs.getBlockSize();
		             return  nTotalBlocks * nBlocSize / 1024 / 1024;
		          }
		          else{
		        	  return -1;
		          }
	 }
	 
	 /*
	  * 返回SD卡可用容量  --#
	  */
	public static long getUsableStorage(){
		String sDcString = android.os.Environment.getExternalStorageState();
		  
         if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {
             File pathFile = android.os.Environment
                     .getExternalStorageDirectory();
 
             android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());
        	 
         // 获取可供程序使用的Block的数量
             long nAvailaBlock = statfs.getAvailableBlocks();

             long nBlocSize = statfs.getBlockSize();

         // 计算 SDCard 剩余大小MB
             return nAvailaBlock * nBlocSize / 1024 / 1024;
         }
         else{
        	 return -1;
         }
         
 
	 }
	
}
 

 

参考:百度文库,开源社区,新浪博客。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics