您的位置:首页 > 移动开发 > Android开发

Android sdcard读写文件(二)

2014-12-07 13:44 363 查看
继续说sdcard读写文件的情况,这篇博客说的是在sdcard根目录中读写文件,着重的而是多种方式的读写文件。直接给出代码:

FileService.java

package com.llp.classdifine;

import java.io.BufferedWriter;
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 java.io.OutputStreamWriter;

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

public class FileService {
	private Context context;
	private String mPath = Environment.getExternalStorageDirectory().getPath()
			+ "/datas";

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

	/**
	 * 保存内容到sd卡中(以私有文件形式保存)
	 * 
	 * @param filename
	 *            文件名称
	 * @param content
	 *            文件内容
	 * @throws Exception
	 */
	public void save2sdCard(String fileName, String content) throws Exception {
		File file = new File(Environment.getExternalStorageDirectory(),
				fileName);
		FileOutputStream outputStream = new FileOutputStream(file);
		outputStream.write(content.getBytes());
		outputStream.close();
	}

	/**
	 * 保存内容(以私有文件形式保存)
	 * 
	 * @param filename
	 *            文件名称
	 * @param content
	 *            文件内容
	 * @throws Exception
	 */
	public void save(String fileName, String content) throws Exception {
		FileOutputStream outputStream = context.openFileOutput(fileName,
				Context.MODE_PRIVATE);
		outputStream.write(content.getBytes());
		outputStream.close();
	}

	/**
	 * 保存内容(以私有文件形式保存+追加)
	 * 
	 * @param filename
	 *            文件名称
	 * @param content
	 *            文件内容
	 * @throws Exception
	 */
	public void saveAppend(String fileName, String content) throws Exception {
		FileOutputStream outputStream = context.openFileOutput(fileName,
				Context.MODE_APPEND);
		outputStream.write(content.getBytes());
		outputStream.close();
	}

	/**
	 * 保存内容(允许其他应用读取)
	 * 
	 * @param filename
	 *            文件名称
	 * @param content
	 *            文件内容
	 * @throws Exception
	 */
	public void saveReadAble(String fileName, String content) throws Exception {
		FileOutputStream outputStream = context.openFileOutput(fileName,
				Context.MODE_WORLD_READABLE);
		outputStream.write(content.getBytes());
		outputStream.close();
	}

	/**
	 * 保存文件到sdcard中某个路径下
	 * @param fileName
	 * @param content
	 */
	public void write2Path(String fileName, String content) {
		File f = new File(mPath + "/" + fileName + ".txt");
		try {
			FileOutputStream fileOS = new FileOutputStream(f);
			try {
				fileOS.write(content.getBytes());
				fileOS.close();
				BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(
						fileOS));
				buf.write(content, 0, content.length());
				buf.flush();
				buf.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 从sdcard中的某个路径下读取文件
	 * @param fileName
	 * @return
	 */
	public String readFromPath(String fileName) {
		byte[] data = new byte[1024];
		try {
			FileInputStream fileIS = new FileInputStream(mPath + "/" + fileName
					+ ".txt");
			// BufferedReader buf = new BufferedReader(new
			// InputStreamReader(in))
			byte[] buffer = new byte[1024];
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			int len = -1;
			while ((len = fileIS.read(buffer)) != -1) {// 读取文件到缓冲区
				byteArrayOutputStream.write(buffer, 0, len);// 写入到内存
			}
			data = byteArrayOutputStream.toByteArray();// 将内存中的二进制数据转为数组
			byteArrayOutputStream.close();
			fileIS.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new String(data);
	}

	/**
	 * 文件读取
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public String read(String fileName) throws Exception {
		FileInputStream inputStream = context.openFileInput(fileName);
		byte[] buffer = new byte[1024];
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		int len = -1;
		while ((len = inputStream.read(buffer)) != -1) {// 读取文件到缓冲区
			byteArrayOutputStream.write(buffer, 0, len);// 写入到内存
		}
		byte[] data = byteArrayOutputStream.toByteArray();// 将内存中的二进制数据转为数组
		byteArrayOutputStream.close();
		inputStream.close();
		return new String(data);
	}
}


MainActivity.java文件:

package com.example.sdcard;

import java.io.File;
import com.example.sdcard.FileService;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */
	private static final String TAG = "MainActivity";
	private FileService fileService;
	String fileName;
	String content;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		File sd = Environment.getExternalStorageDirectory();
		String mPath = sd.getPath() + "/datas";
		File file = new File(mPath);
		if (!file.exists()) {
			file.mkdir();
		}
		Log.v("test", "file.getPath()" + file.getPath());
		Button button = (Button) findViewById(R.id.btnsave);
		Button read = (Button) findViewById(R.id.btnread);
		fileService = new FileService(this);
		// File file = this.getFilesDir();// 快速得到文件夹
		// this.getCacheDir();// 获得缓存文件夹
		final EditText fileNameText = (EditText) findViewById(R.id.fileName);
		final EditText contenText = (EditText) findViewById(R.id.content);
		final EditText readtext = (EditText) findViewById(R.id.contentread);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				fileName = fileNameText.getText().toString();
				content = contenText.getText().toString();
				try {
					// 判断sd卡是否存在手机上并且可以进行读写
					if (Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						fileService.write2Path(fileName, content);
					} else {
					}
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
			}
		});
		read.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				try {
					// 判断sd卡是否存在手机上并且可以进行读写
					if (Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						fileName = fileNameText.getText().toString();
						Log.v("test", "fileName" + fileName);
						readtext.setText(fileService.readFromPath(fileName));
					} else {
					}
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
			}
		});
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: