Android 自动创建文件到scard卡并保存

直接上Activity代码:


public class DRMPTestActivity extends Activity implements OnClickListener{
    
    String fileName = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }


	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.save:
			Time t = new Time();
			t.setToNow();
			//定义文件名称
			fileName = "DRMP-" + t.year + t.month + t.monthDay
					+ t.hour + t.minute + ".txt";
			final EditText fileText =  new EditText(DRMPTestActivity.this);
			fileText.setText(fileName);
			// 定义一个对话框
			new AlertDialog.Builder(DRMPTestActivity.this)
				.setTitle("请输入文件名")// 标题
				.setIcon(android.R.drawable.ic_dialog_info)// 图标
				.setView(fileText)// 为对话框传入了一个文本编辑框
				.setPositiveButton("确定",
					// 对话框监听事件
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
									int whichButton) {
							String temp = fileText.getText().toString();
							if (temp != null || temp != ""){
								fileName = temp;
							}
							String data = “哈回家啊就是开始卡”;
							
							WriteData(fileName, data);
							Toast.makeText(getApplicationContext(), "\""+fileName+"\"正在保存...", Toast.LENGTH_LONG)
							.show();
						}
					}).setNegativeButton("取消", null).show();
			
			break;
		}
		
	}  
	
	// 将数据存储到SD卡,filename为文件名,data为要存储的内容
	private void WriteData(String fileName, String data) {
		FileService fileService = new FileService(getApplicationContext());
		try {
			// 判断SDCard是否存在并且可以读写
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				fileService.saveToSD(fileName, data);
			} else {
				
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
fileService代码:

package com.cmdi.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

public class FileService {

	private Context context;

	public FileService(Context context) {
		super();
		this.context = context;
	}

	/**
	 * 写入文件到SD卡
	 * 
	 * @throws IOException
	 */
	public void saveToSD(String fileNameStr, String fileContentStr)
			throws IOException {

		// 备注:Java File类能够创建文件或者文件夹,但是不能两个一起创建
		File file = new File("/mnt/sdcard/DRMP");

		if (!file.exists()) {
			file.mkdir();
		}
		File file1 = new File(file, fileNameStr);

		FileOutputStream fos = new FileOutputStream(file1,true);
		fos.write(fileContentStr.getBytes());
		fos.close();
		
		
	}

	/**
	 * 保存文件到手机
	 * 
	 * @param fileNameStr
	 *            文件名
	 * @param fileContentStr
	 *            文件内容
	 * @throws IOException
	 */
	public void save(String fileNameStr, String fileContentStr)
			throws IOException {
		// 私有操作模式:创建出来的文件只能被本应用访问,其它应用无法访问该文件,另外采用私有操作模式创建的文件,写入文件中的内容会覆盖原文件的内容
		FileOutputStream fos = context.openFileOutput(fileNameStr,
				context.MODE_PRIVATE);
		fos.write(fileContentStr.getBytes());
		fos.close();
	}

	public void saveAppend(String fileNameStr, String fileContentStr)
			throws IOException {
		// 追加操作模式:不覆盖源文件,但是同样其它应用无法访问该文件
		FileOutputStream fos = context.openFileOutput(fileNameStr,
				context.MODE_APPEND);
		fos.write(fileContentStr.getBytes());
		fos.close();
	}

	public void saveReadable(String fileNameStr, String fileContentStr)
			throws IOException {
		// 读取操作模式:可以被其它应用读取,但不能写入
		FileOutputStream fos = context.openFileOutput(fileNameStr,
				context.MODE_WORLD_READABLE);
		fos.write(fileContentStr.getBytes());
		fos.close();
	}

	public void saveWriteable(String fileNameStr, String fileContentStr)
			throws IOException {
		// 写入操作模式:可以被其它应用写入,但不能读取
		FileOutputStream fos = context.openFileOutput(fileNameStr,
				context.MODE_WORLD_WRITEABLE);
		fos.write(fileContentStr.getBytes());
		fos.close();
	}

	public void saveReadWriteable(String fileNameStr, String fileContentStr)
			throws IOException {
		// 读写操作模式:可以被其它应用读写
		FileOutputStream fos = context.openFileOutput(fileNameStr,
				context.MODE_WORLD_READABLE + context.MODE_WORLD_WRITEABLE);
		fos.write(fileContentStr.getBytes());
		fos.close();
	}

	/**
	 * 读取文件内容
	 * 
	 * @param fileNamestr
	 *            文件名
	 * @return
	 * @throws IOException
	 */
	public String read(String fileNamestr) throws IOException {
		FileInputStream fis = context.openFileInput(fileNamestr);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		byte[] data = bos.toByteArray();

		return new String(data);
	}

}
注意:在主配置文件中需要添加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

以上是其主要代码,想下载DEMO的可以到这个地址http://download.csdn.net/detail/yusewuhen/6653785下载,注意由于这个Demo还有文件上传功能所以还需要你自己修改,选择其中有用的部分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值