Android 文件读写存储
应用私有存储文件的写入与读取 - openFileInput 和 openFileOutput
应用私有存储文件:
/data/data/<package name>/files/目录下
应用删除时,即清空该目录。
//通过context对象获取私有目录:/data/data/packagename/files
context.getFileDir().getPath()
Context对象中文操作的API及说明
方法名 | 说明 |
openFileInput(String filename) | 打开应用程序私有目录下的的指定私有文件以读入数据,返回一个FileInputStream 对象 |
openFileOutput(String filename, 操作模式) |
打开应用程序私有目录下的的指定私有文件以写入数据,返回一个FileOutputStream 对象, 如果文件不存在就创建这个文件。 |
fileList() | 搜索应用程序私有文件夹下的私有文件,返回所有文件名的String数组 |
deleteFile(String fileName) | 删除指定文件名的文件,成功返回true,失败返回false |
filename :不能包含路径分隔符“/” ,如果文件不存在,Android会自动创建它。创建的文件保存在/data/data/<package name>/files目录
在使用openFileOutput方法打开文件以写入数据时,需要指定打开模式。默认为零,即MODE_PRIVATE。不同的模式对应的的含义如下:
openFileOutput方法打开文件时的模式:
常量 | 含义 |
MODE_PRIVATE | 默认模式,文件只可以被调用该方法的应用程序访问 |
MODE_APPEND | 如果文件已存在就向该文件的末尾继续写入数据,而不是覆盖原来的数据。 |
MODE_WORLD_READABLE | 赋予所有的应用程序对该文件读的权限。 |
MODE_WORLD_WRITEABLE | 赋予所有的应用程序对该文件写的权限。 |
e.g.
1 package com.fileoperate; 2 3 4 import java.io.FileInputStream; 5 6 import java.io.FileOutputStream; 7 8 import android.app.Activity; 9 10 import android.graphics.Color; 11 12 import android.os.Bundle; 13 14 import android.widget.TextView; 15 16 17 public class FileOperationActivity extends Activity{ 18 19 //文件名称 21 String fileName = "test.txt"; 22 23 //写入和读出的数据信息 24 String content = "demo"; 25 26 TextView tv_content; 27 28 @Override 30 protected void onCreate(Bundle savedInstanceState) { 31 32 super.onCreate(savedInstanceState); 33 34 setContentView(R.layout.main); 35 36 writeFileData(fileName, content); // 写入文件 37 38 String result = readFileData(fileName); // 读取文件 39 40 tv_content = (TextView) findViewById(R.id.tv_content); 41 42 tv_content.setText(result); 43 } 44 45 //向指定的文件中写入指定的数据 47 public void writeFileData(String filename, String content){ 48 49 try { 50 51 FileOutputStream fos = this.openFileOutput(filename, MODE_PRIVATE);//获得FileOutputStream 52 53 //将要写入的字符串转换为byte数组 54 55 byte[] bytes = content.getBytes(); 56 57 fos.write(bytes);//将byte数组写入文件 58 59 fos.close();//关闭文件输出流 60 61 } catch (Exception e) { 63 e.printStackTrace(); 65 } 67 } 70 71 //打开指定文件,读取其数据,返回字符串对象 73 public String readFileData(String fileName){ 74 75 String result=""; 76 77 try{ 78 79 FileInputStream fis = thisopenFileInput(fileName); 80 81 //获取文件长度 83 int lenght = fis.available(); 84 85 byte[] buffer = new byte[lenght]; 86 87 fis.read(buffer); 88 89 //将byte数组转换成指定格式的字符串 91 result = new String(buffer, "UTF-8"); 92 93 } catch (Exception e) { 95 e.printStackTrace(); 97 } 98 99 return result; 101 } 103 }
SD card 文件 读写
FileInputStream
读取文件内容:
1 public static String read(String fileName) { 2 3 FileInputStream fis = null; 4 String result = null; 5 6 try { 7 8 File file = new File(Environment.getExternalStorageDirectory(), fileName + ".txt"); 9 10 fis = new FileInputStream(file); 11 12 byte[] buffer = new byte[fis.available()]; 13 fis.read(buffer); 14 fis.close(); 15 16 result = new String(buffer, "UTF-8"); 17 18 } catch (Exception ex) { 19 20 ex.printStackTrace(); 21 22 try { 23 if (fis != null) { 24 fis.close(); 25 } 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 } 30 31 return result; 32 }
BufferReader
读取文件
1 try { 2 File file = new File(Environment.getExternalStorageDirectory(), 3 DEFAULT_FILENAME); 4 BufferedReader br = new BufferedReader(new FileReader(file)); 5 String readline = ""; 6 StringBuffer sb = new StringBuffer(); 7 while ((readline = br.readLine()) != null) { 8 System.out.println("readline:" + readline); 9 sb.append(readline); 10 } 11 br.close(); 12 System.out.println("读取成功:" + sb.toString()); 13 } catch (Exception e) { 14 e.printStackTrace(); 15 }
FileOutputStream
写入文件内容:覆盖原本内容(先清空原有内容,再写入)
1 /* 2 * 定义文件保存的方法,写入到文件中,所以是输出流 3 * */ 4 public static void save(String fileName, String content) { 5 FileOutputStream fos = null; 6 try { 7 8 /* 判断sd的外部设置状态是否可以读写 */ 9 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 10 11 File file = new File(Environment.getExternalStorageDirectory(), fileName + ".txt"); 12 13 // 先清空内容再写入 14 fos = new FileOutputStream(file); 15 16 byte[] buffer = content.getBytes(); 17 fos.write(buffer); 18 fos.close(); 19 } 20 21 } catch (Exception ex) { 22 23 ex.printStackTrace(); 24 25 try { 26 if (fos != null) { 27 fos.close(); 28 } 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 } 33 }
RandomAccessFile:
追加内容:在原有的内容基础上追加内容
1 public static void write(String content) { 2 try { 3 //判断实际是否有SD卡,且应用程序是否有读写SD卡的能力,有则返回true 4 if (Environment.getExternalStorageState().equals( 5 Environment.MEDIA_MOUNTED)) { 6 // 获取SD卡的目录 7 File sdCardDir = Environment.getExternalStorageDirectory(); 8 String path = "/test/"; 9 File dir = new File(sdCardDir + path); 10 if (!dir.exists()) { 11 dir.mkdirs(); 12 } 13 File targetFile = new File(sdCardDir.getCanonicalPath() + path+"aaa.txt"); 14 //使用RandomAccessFile是在原有的文件基础之上追加内容, 15 //而使用outputstream则是要先清空内容再写入 16 RandomAccessFile raf = new RandomAccessFile(targetFile, "rw"); 17 //光标移到原始文件最后,再执行写入 18 raf.seek(targetFile.length()); 19 raf.write(content.getBytes()); 20 raf.close(); 21 } 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 }
BufferedWriter
Writer类就是为写文本而设计的。使用BufferedWriter写入文本时不需要将文本转换成字节数组.
这里有一个 "修饰类 "的概念
FileWriter 是被修饰者
BufferedWriter 是修饰者
一般用法为
BufferedWriter bw = new BufferedWriter(new FileWriter("filename"));
上面这个加了一个缓冲,缓冲写满后在将数据写入硬盘
这样做极大的提高了性能
如果单独使用 FileWriter 也可以
你每写一个数据,硬盘就有一个写动作,性能极差
1 try { 2 3 File file = new File(Environment.getExternalStorageDirectory(), 4 DEFAULT_FILENAME); 6 /** 7 * 为了提高写入的效率,使用了字符流的缓冲区。 8 * 创建了一个字符写入流的缓冲区对象,并和指定要被缓冲的流对象相关联。 9 */ 10 //第二个参数意义是说是否以append方式添加内容 11 BufferedWriter bw = new BufferedWriter(new FileWriter(file, true)); 12 13 //使用缓冲区中的方法将数据写入到缓冲区中。 14 bw.write("hello world !"); 15 bw.newLine(); 16 bw.newLine(); 17 bw.write("test"); 18 bw.write("content"); 19 //使用缓冲区中的方法,将数据刷新到目的地文件中去。 20 bw.flush(); 21 //关闭缓冲区,同时关闭了FileWriter流对象 22 bw.close(); 23 System.out.println("写入成功"); 24 25 } catch (Exception e) { 26 e.printStackTrace(); 27 }
/data/data: context.getFileDir().getPath();
是一个应用程序的私有目录,只有当前应用程序有权限访问读写,其他应用无权限访问。一些安全性要求比较高的数据存放在该目录,一般用来存放size比较小的数据。
/sdcard: Enviroment.getExternalStorageDirectory().getPath();
是一个外部存储目录,只用应用声明了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>的一个权限,就可以访问读写sdcard目录;所以一般用来存放一些安全性不高的数据,文件size比较大的数据。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步