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

From:http://blog.csdn.net/llp1992/article/details/41786993

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

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

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

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

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

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

  1. private String mPath = Environment.getExternalStorageDirectory().getPath()+ "/datas";

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


  1. public void write2Path(String fileName, String content) {
  2. File f = new File(mPath + "/" + fileName + ".txt");
  3. try {
  4. FileOutputStream fileOS = new FileOutputStream(f);
  5. try {
  6. fileOS.write(content.getBytes());
  7. fileOS.close();
  8. BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(
  9. fileOS));
  10. buf.write(content, 0, content.length());
  11. buf.flush();
  12. buf.close();
  13. } catch (IOException e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. }
  17. } catch (FileNotFoundException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. }
  21. }
	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();
		}
	}
接着是从保存文件的那个路径读取我们保存的文件的函数:

  1. public String readFromPath(String fileName) {
  2. byte[] data = new byte[1024];
  3. try {
  4. FileInputStream fileIS = new FileInputStream(mPath + "/" + fileName
  5. + ".txt");
  6. // BufferedReader buf = new BufferedReader(new
  7. // InputStreamReader(in))
  8. byte[] buffer = new byte[1024];
  9. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  10. int len = -1;
  11. while ((len = fileIS.read(buffer)) != -1) {// 读取文件到缓冲区
  12. byteArrayOutputStream.write(buffer, 0, len);// 写入到内存
  13. }
  14. data = byteArrayOutputStream.toByteArray();// 将内存中的二进制数据转为数组
  15. byteArrayOutputStream.close();
  16. fileIS.close();
  17. } catch (FileNotFoundException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. return new String(data);
  25. }
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

  1. package com.llp.classdifine;
  2. import java.io.BufferedWriter;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.OutputStreamWriter;
  10. import android.content.Context;
  11. import android.os.Environment;
  12. public class FileService {
  13. private Context context;
  14. private String mPath = Environment.getExternalStorageDirectory().getPath()
  15. + "/datas";
  16. public FileService(Context context) {
  17. this.context = context;
  18. }
  19. /**
  20. * 保存文件到sdcard中某个路径下
  21. * @param fileName
  22. * @param content
  23. */
  24. public void write2Path(String fileName, String content) {
  25. File f = new File(mPath + "/" + fileName + ".txt");
  26. try {
  27. FileOutputStream fileOS = new FileOutputStream(f);
  28. try {
  29. fileOS.write(content.getBytes());
  30. fileOS.close();
  31. BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(
  32. fileOS));
  33. buf.write(content, 0, content.length());
  34. buf.flush();
  35. buf.close();
  36. } catch (IOException e) {
  37. // TODO Auto-generated catch block
  38. e.printStackTrace();
  39. }
  40. } catch (FileNotFoundException e) {
  41. // TODO Auto-generated catch block
  42. e.printStackTrace();
  43. }
  44. }
  45. /**
  46. * 从sdcard中的某个路径下读取文件
  47. * @param fileName
  48. * @return
  49. */
  50. public String readFromPath(String fileName) {
  51. byte[] data = new byte[1024];
  52. try {
  53. FileInputStream fileIS = new FileInputStream(mPath + "/" + fileName
  54. + ".txt");
  55. // BufferedReader buf = new BufferedReader(new
  56. // InputStreamReader(in))
  57. byte[] buffer = new byte[1024];
  58. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  59. int len = -1;
  60. while ((len = fileIS.read(buffer)) != -1) {// 读取文件到缓冲区
  61. byteArrayOutputStream.write(buffer, 0, len);// 写入到内存
  62. }
  63. data = byteArrayOutputStream.toByteArray();// 将内存中的二进制数据转为数组
  64. byteArrayOutputStream.close();
  65. fileIS.close();
  66. } catch (FileNotFoundException e) {
  67. // TODO Auto-generated catch block
  68. e.printStackTrace();
  69. } catch (IOException e) {
  70. // TODO Auto-generated catch block
  71. e.printStackTrace();
  72. }
  73. return new String(data);
  74. }
  75. }
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代码如下:
  1. package com.example.sdcard;
  2. import java.io.File;
  3. import com.example.sdcard.FileService;
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6. import android.os.Environment;
  7. import android.util.Log;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. public class MainActivity extends Activity {
  13. /** Called when the activity is first created. */
  14. private static final String TAG = "MainActivity";
  15. private FileService fileService;
  16. String fileName;
  17. String content;
  18. @Override
  19. public void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_main);
  22. File sd = Environment.getExternalStorageDirectory();
  23. String mPath = sd.getPath() + "/datas";
  24. File file = new File(mPath);
  25. if (!file.exists()) {
  26. file.mkdir();
  27. }
  28. Log.v("test", "file.getPath()" + file.getPath());
  29. Button button = (Button) findViewById(R.id.btnsave);
  30. Button read = (Button) findViewById(R.id.btnread);
  31. fileService = new FileService(this);
  32. // File file = this.getFilesDir();// 快速得到文件夹
  33. // this.getCacheDir();// 获得缓存文件夹
  34. final EditText fileNameText = (EditText) findViewById(R.id.fileName);
  35. final EditText contenText = (EditText) findViewById(R.id.content);
  36. final EditText readtext = (EditText) findViewById(R.id.contentread);
  37. button.setOnClickListener(new View.OnClickListener() {
  38. @Override
  39. public void onClick(View v) {
  40. fileName = fileNameText.getText().toString();
  41. content = contenText.getText().toString();
  42. try {
  43. // 判断sd卡是否存在手机上并且可以进行读写
  44. if (Environment.getExternalStorageState().equals(
  45. Environment.MEDIA_MOUNTED)) {
  46. fileService.write2Path(fileName, content);
  47. } else {
  48. }
  49. } catch (Exception e) {
  50. Log.e(TAG, e.toString());
  51. }
  52. }
  53. });
  54. read.setOnClickListener(new View.OnClickListener() {
  55. @Override
  56. public void onClick(View v) {
  57. // TODO Auto-generated method stub
  58. try {
  59. // 判断sd卡是否存在手机上并且可以进行读写
  60. if (Environment.getExternalStorageState().equals(
  61. Environment.MEDIA_MOUNTED)) {
  62. fileName = fileNameText.getText().toString();
  63. Log.v("test", "fileName" + fileName);
  64. readtext.setText(fileService.readFromPath(fileName));
  65. } else {
  66. }
  67. } catch (Exception e) {
  68. Log.e(TAG, e.toString());
  69. }
  70. }
  71. });
  72. }
  73. }  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值