android开发 SD卡存储

(新手笔记,参考谨慎)

关于sd卡的存读删,网上有很多例子。但是一般都是以存储.txt文件为例,当要将音乐文件存入sd卡该如何呢?

public class SDcardData {
	public static final String STORE_PATH = Environment.getExternalStorageDirectory() + "/ting/";
	/**
	 * 
	 * @param filename
	 * @return /sdcard/ting/filename
	 */
	public static File createFile(String filename) {
        return createFile(STORE_PATH, filename);
    }
	public static File createFile(String path, String filename) {
        File file = createDir(path);
        File dir = new File(file, filename);  
        if (!dir.exists()) {  
              try {  
                  //在指定的文件夹中创建文件  
                  dir.createNewFile();  
            } catch (Exception e) {  
            }  
        }  
        return dir;
    }
	public static File createDir(String path){
        File file = new File(path);  
        if (!file.exists()) {  
            try {  
                file.mkdirs();  
            } catch (Exception e) {  
            }  
        } 
        return file;
	}
	/**
	 * 将一个InputStream里面的数据写入到SD卡中
	 * 
	 * @param path
	 * @param fileName
	 * @param input
	 * @return
	 */
	public File writeToSDFromInput(String fileName, InputStream input){
		File file = null;
		OutputStream output = null;
		try {
			file = createFile(fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			while((input.read(buffer)) != -1){
				output.write(buffer);
			}
			//清缓存,将流中的数据保存到文件中
			output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		finally{
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file;
	}
	
	/**
	 * 
	 * @param filename
	 * @return
	 */
	public static File getFile(String filename){
		return getFile(STORE_PATH, filename);
	}
	public static File getFile(String path, String filename){
		if(UtilsString.isEmpty(filename)) return null;
		File dir = createDir(path);
		return new File(dir, filename);
	}
	
	/**
	 * 
	 * @param filename
	 */
	public static void deleteFiles(String filename){
		File f = getFile(filename);
		if(f!= null && f.exists())
			f.delete();
	}
	
	
}


=================

在用的时候:将音乐文件以数据流存入

SDcardData localVoice = new SDcardData();
				String path1 = Environment.getExternalStorageDirectory().getAbsolutePath();
				File file1 = new File(path1 + "/audiorecordtest.mp4");
				if(file1.exists()){
					FileInputStream fis;
					try {
						fis = new FileInputStream(file1);
						localVoice.writeToSDFromInput(localVoiceId+".MP4", fis);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
//					Toast.makeText(getActivity(), "保存成功", 1).show();
				}


关于读操作和删除操作这里不赘述了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值