Android SdCard 新建文件夹并在文件夹中读、写文件

首先你要获取SdCard的读写权限:

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我们现在SdCard中新建一个文件夹:名字为 datas

File sd = Environment.getExternalStorageDirectory();
String mPath = sd.getPath() + "/datas";
File file = new File(mPath);
if (!file.exists()) {
	file.mkdir();
}

然后定义一个FileService类用于存放那些读写的函数:

首先我们还是要定义一下我们的文件路径:

private String mPath = Environment.getExternalStorageDirectory().getPath()+ "/datas";
接下来是保存文件到 SdCard中某个目录下的函数:保存类型是txt文本

	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();
		}
	}
接着是从保存文件的那个路径读取我们保存的文件的函数:

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);
	}

完整的FileService类如下:

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;
	}
	/**
	 * 保存文件到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);
	}
}

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());
				}
			}
		});
	}
}






你可能感兴趣的:(android,sdcard读写数据,sdcard新建文件夹)