文件读写操作(含SDCard的读写)

1.在AndroidManifest文件下添加SDCard的读写权限

  1. <!-- 在SDCard中创建与删除文件权限 -->
  2. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  3. <!-- 往SDCard写入数据权限 -->
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  1. <!-- 在SDCard中创建与删除文件权限 -->  
  2.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
  3.     <!-- 往SDCard写入数据权限 -->  
  4.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

2.文件操作的各种模式如下代码:(注意通过getExternalStorageDirectory方法获取SDCard的文件路径)

  1. package com.hoo.file;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import android.content.Context;
  7. import android.os.Environment;
  8. public class FileService
  9. {
  10. private Context context;
  11. public FileService(Context context)
  12. {
  13. this.context = context;
  14. }
  15. /**
  16. * 读取文件的内容
  17. * @param filename 文件名称
  18. * @return
  19. * @throws Exception
  20. */
  21. public String readFile(String filename) throws Exception
  22. {
  23. //获得输入流
  24. FileInputStream inStream = context.openFileInput(filename);
  25. //new一个缓冲区
  26. byte[] buffer = new byte[1024];
  27. int len = 0;
  28. //使用ByteArrayOutputStream类来处理输出流
  29. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  30. while( (len = inStream.read(buffer))!= -1)
  31. {
  32. //写入数据
  33. outStream.write(buffer, 0, len);
  34. }
  35. //得到文件的二进制数据
  36. byte[] data = outStream.toByteArray();
  37. //关闭流
  38. outStream.close();
  39. inStream.close();
  40. return new String(data);
  41. }
  42. /**
  43. * 以默认私有方式保存文件内容至SDCard中
  44. * @param filename
  45. * @param content
  46. * @throws Exception
  47. */
  48. public void saveToSDCard(String filename, String content) throws Exception
  49. {
  50. //通过getExternalStorageDirectory方法获取SDCard的文件路径
  51. File file = new File(Environment.getExternalStorageDirectory(), filename);
  52. //获取输出流
  53. FileOutputStream outStream = new FileOutputStream(file);
  54. outStream.write(content.getBytes());
  55. outStream.close();
  56. }
  57. /**
  58. * 以默认私有方式保存文件内容,存放在手机存储空间中
  59. * @param filename
  60. * @param content
  61. * @throws Exception
  62. */
  63. public void save(String filename, String content) throws Exception
  64. {
  65. //
  66. FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
  67. outStream.write(content.getBytes());
  68. outStream.close();
  69. }
  70. /**
  71. * 以追加的方式保存文件内容
  72. * @param filename 文件名称
  73. * @param content 文件内容
  74. * @throws Exception
  75. */
  76. public void saveAppend(String filename, String content) throws Exception
  77. {
  78. FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_APPEND);
  79. outStream.write(content.getBytes());
  80. outStream.close();
  81. }
  82. /**
  83. * 以允许其他应用从该文件中读取内容的方式保存文件(Context.MODE_WORLD_READABLE)
  84. * @param filename 文件名称
  85. * @param content 文件内容
  86. * @throws Exception
  87. */
  88. public void saveReadable(String filename, String content) throws Exception
  89. {
  90. FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
  91. outStream.write(content.getBytes());
  92. outStream.close();
  93. }
  94. /**
  95. * 以允许其他应用往该文件写入内容的方式保存文件
  96. * @param filename 文件名称
  97. * @param content 文件内容
  98. * @throws Exception
  99. */
  100. public void saveWriteable(String filename, String content) throws Exception
  101. {
  102. FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
  103. outStream.write(content.getBytes());
  104. outStream.close();
  105. }
  106. /**
  107. * 以允许其他应用对该文件读和写的方式保存文件(MODE_WORLD_READABLE与MODE_WORLD_WRITEABLE)
  108. * @param filename 文件名称
  109. * @param content 文件内容
  110. * @throws Exception
  111. */
  112. public void saveRW(String filename, String content) throws Exception
  113. {
  114. FileOutputStream outStream = context.openFileOutput(filename,
  115. Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
  116. //Context.MODE_WORLD_READABLE(1) + Context.MODE_WORLD_WRITEABLE(2),其实可用3替代
  117. outStream.write(content.getBytes());
  118. outStream.close();
  119. }
  120. }
  1. package com.hoo.file;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import android.content.Context;  
  7. import android.os.Environment;  
  8. public class FileService   
  9. {  
  10.     private Context context;  
  11.     public FileService(Context context)   
  12.     {  
  13.         this.context = context;  
  14.     }  
  15.       
  16.     /** 
  17.      * 读取文件的内容 
  18.      * @param filename 文件名称 
  19.      * @return 
  20.      * @throws Exception 
  21.      */  
  22.     public String readFile(String filename) throws Exception  
  23.     {  
  24.         //获得输入流   
  25.         FileInputStream inStream = context.openFileInput(filename);  
  26.         //new一个缓冲区   
  27.         byte[] buffer = new byte[1024];  
  28.         int len = 0;  
  29.         //使用ByteArrayOutputStream类来处理输出流   
  30.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  31.         while( (len = inStream.read(buffer))!= -1)  
  32.         {  
  33.             //写入数据   
  34.             outStream.write(buffer, 0, len);  
  35.         }  
  36.         //得到文件的二进制数据   
  37.         byte[] data = outStream.toByteArray();  
  38.         //关闭流   
  39.         outStream.close();  
  40.         inStream.close();  
  41.         return new String(data);  
  42.     }  
  43.     /** 
  44.      * 以默认私有方式保存文件内容至SDCard中 
  45.      * @param filename  
  46.      * @param content  
  47.      * @throws Exception 
  48.      */  
  49.     public void saveToSDCard(String filename, String content) throws Exception  
  50.     {  
  51.         //通过getExternalStorageDirectory方法获取SDCard的文件路径   
  52.         File file = new File(Environment.getExternalStorageDirectory(), filename);  
  53.         //获取输出流   
  54.         FileOutputStream outStream = new FileOutputStream(file);  
  55.         outStream.write(content.getBytes());  
  56.         outStream.close();  
  57.     }  
  58.       
  59.     /** 
  60.      * 以默认私有方式保存文件内容,存放在手机存储空间中 
  61.      * @param filename  
  62.      * @param content  
  63.      * @throws Exception 
  64.      */  
  65.     public void save(String filename, String content) throws Exception  
  66.     {  
  67.         //   
  68.         FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);  
  69.         outStream.write(content.getBytes());  
  70.         outStream.close();  
  71.     }  
  72.       
  73.     /** 
  74.      * 以追加的方式保存文件内容 
  75.      * @param filename 文件名称 
  76.      * @param content 文件内容 
  77.      * @throws Exception 
  78.      */  
  79.     public void saveAppend(String filename, String content) throws Exception  
  80.     {     
  81.         FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_APPEND);  
  82.         outStream.write(content.getBytes());  
  83.         outStream.close();  
  84.     }  
  85.       
  86.     /** 
  87.      * 以允许其他应用从该文件中读取内容的方式保存文件(Context.MODE_WORLD_READABLE) 
  88.      * @param filename 文件名称 
  89.      * @param content 文件内容 
  90.      * @throws Exception 
  91.      */  
  92.     public void saveReadable(String filename, String content) throws Exception  
  93.     {  
  94.         FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);  
  95.         outStream.write(content.getBytes());  
  96.         outStream.close();  
  97.     }  
  98.       
  99.     /** 
  100.      * 以允许其他应用往该文件写入内容的方式保存文件 
  101.      * @param filename 文件名称 
  102.      * @param content 文件内容 
  103.      * @throws Exception 
  104.      */  
  105.     public void saveWriteable(String filename, String content) throws Exception  
  106.     {  
  107.         FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);  
  108.         outStream.write(content.getBytes());  
  109.         outStream.close();  
  110.     }  
  111.       
  112.     /** 
  113.      * 以允许其他应用对该文件读和写的方式保存文件(MODE_WORLD_READABLE与MODE_WORLD_WRITEABLE) 
  114.      * @param filename 文件名称 
  115.      * @param content 文件内容 
  116.      * @throws Exception 
  117.      */  
  118.     public void saveRW(String filename, String content) throws Exception  
  119.     {  
  120.         FileOutputStream outStream = context.openFileOutput(filename,  
  121.                 Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);  
  122.         //Context.MODE_WORLD_READABLE(1) + Context.MODE_WORLD_WRITEABLE(2),其实可用3替代   
  123.         outStream.write(content.getBytes());  
  124.         outStream.close();  
  125.     }  
  126. }  

3.写入数据前判断sdcard是否存在于手机上,是否有写保护

  1. package com.hoo.file;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.os.Environment;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.Toast;
  10. public class MainActivity extends Activity
  11. {
  12. private static final String TAG = "MainActivity";
  13. private FileService fileService;
  14. @Override
  15. public void onCreate(Bundle savedInstanceState)
  16. {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. fileService = new FileService(this);
  20. //使用下面的方法可以快速获取当前文件夹的位置,
  21. //这样可以在后面追加路径从而避免使用绝对路径
  22. //File filedir = this.getFilesDir();
  23. Button button = (Button) this.findViewById(R.id.button);
  24. button.setOnClickListener(new View.OnClickListener()
  25. {
  26. @Override
  27. public void onClick(View v)
  28. {
  29. //获取EditText中的内容
  30. EditText filenameText = (EditText) findViewById(R.id.filename);
  31. EditText contentText = (EditText) findViewById(R.id.filecontent);
  32. String filename = filenameText.getText().toString();
  33. String content = contentText.getText().toString();
  34. try
  35. {
  36. //使用通常文件保存方式,默认保存在data/data/包名/file/XXX里面
  37. //fileService.save(filename, content);
  38. //判断sdcard是否存在于手机上而且没有写保护
  39. //Android2.2版本以后sdcard的路径在mnt/sdcard,2.2之前在/sdcard
  40. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
  41. {
  42. //保存到SDCard中
  43. fileService.saveToSDCard(filename, content);
  44. //提示保存成功
  45. Toast.makeText(MainActivity.this, R.string.success, 1).show();
  46. }
  47. else
  48. {
  49. //提示保存失败
  50. Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();
  51. }
  52. }
  53. catch (Exception e)
  54. {
  55. Log.e(TAG, e.toString());
  56. Toast.makeText(MainActivity.this, R.string.error, 1).show();
  57. }
  58. }
  59. });
  60. }
  61. }
  1. package com.hoo.file;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.os.Environment;  
  5. import android.util.Log;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. import android.widget.Toast;  
  10. public class MainActivity extends Activity   
  11. {  
  12.     private static final String TAG = "MainActivity";  
  13.     private FileService fileService;  
  14.       
  15.     @Override  
  16.     public void onCreate(Bundle savedInstanceState)   
  17.     {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.        
  21.         fileService = new FileService(this);  
  22.         //使用下面的方法可以快速获取当前文件夹的位置,   
  23.         //这样可以在后面追加路径从而避免使用绝对路径   
  24.         //File filedir = this.getFilesDir();   
  25.         Button button = (Button) this.findViewById(R.id.button);  
  26.         button.setOnClickListener(new View.OnClickListener()   
  27.         {  
  28.             @Override  
  29.             public void onClick(View v)   
  30.             {  
  31.                 //获取EditText中的内容   
  32.                 EditText filenameText = (EditText) findViewById(R.id.filename);  
  33.                 EditText contentText = (EditText) findViewById(R.id.filecontent);  
  34.                 String filename = filenameText.getText().toString();  
  35.                 String content = contentText.getText().toString();  
  36.                 try   
  37.                 {  
  38.                     //使用通常文件保存方式,默认保存在data/data/包名/file/XXX里面   
  39.                     //fileService.save(filename, content);   
  40.                       
  41.                     //判断sdcard是否存在于手机上而且没有写保护   
  42.                     //Android2.2版本以后sdcard的路径在mnt/sdcard,2.2之前在/sdcard   
  43.                     if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))  
  44.                     {  
  45.                         //保存到SDCard中   
  46.                         fileService.saveToSDCard(filename, content);  
  47.                         //提示保存成功   
  48.                         Toast.makeText(MainActivity.this, R.string.success, 1).show();  
  49.                     }  
  50.                     else  
  51.                     {  
  52.                         //提示保存失败   
  53.                         Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();  
  54.                     }  
  55.                 }   
  56.                 catch (Exception e)  
  57.                 {  
  58.                     Log.e(TAG, e.toString());  
  59.                     Toast.makeText(MainActivity.this, R.string.error, 1).show();  
  60.                 }  
  61.             }  
  62.         });  
  63.     }  
  64. }  
原文地址:https://www.cnblogs.com/Free-Thinker/p/3668288.html