android SD卡文件的读写(z)
16lz
2021-01-24
android SD卡文件的读写(z转载) http://www.cnblogs.com/shaoyangjiang/archive/2012/3/9.html
Android文件管理方法
Android使用的是基于Linux的文件系统,对于文件的访问和管理是通过权限设置来限制的.
在Linux系统中,文件权限分别描述了创建者、同组用户和其他用户对文件的操作限制。
x表示可执行,r表示可读,w表示可写,d表示目录, - 表示普通文件。
产生这样的文件权限与程序人员设定的
Android存储文件的类型
(内部存储)程序开发人员可以建立和访问程序自身的私有文件;
(资源存储)可以访问保存在资源目录中的原始文件和XML文件;
(外部存储)可以在SD卡等外部存储设备中保存文件
Android系统允许应用程序创建仅能够自身访问的私有文件,文件保存在设备的内部存储器上,在Linux系统下的 / data / data /< package name >/ files目录中
Android系统不仅支持标准Java的IO类和方法,还提供了能够简化读写流式文件过程的函数
FileOutputStreamopenFileOutput(Stringfilename int mode)
FileInputStreamopenFileInput(Stringfilename)
参数文件不允许包含描述路径的斜杠(其存储位置固定)
访问模式:
MODE_PRIVATE私有模式,缺陷模式,文件仅能够被文件创建程序访问,或具有相同UID的程序访问。
MODE_APPEND追加模式,如果文件已经存在,则在文件的结尾处添加新数据。
MODE_WORLD_READABLE全局读模式,允许任何程序读取私有文件。
MODE_WORLD_WRITEABLE全局写模式,允许任何程序写入私有文件。
三个基本的读方法
abstract int read():读取一个字节数据,并返回读到的数据,如果返回 - 1 ,表示读到了输入流的末尾。
int read( byte []b):将数据读入一个字节数组,同时返回实际读取的字节数。如果返回 - 1 ,表示读到了输入流的末尾。
int read( byte []b, int off, int len):将数据读入一个字节数组,同时返回实际读取的字节数。如果返回 - 1 ,表示读到了输入流的末尾。off指定在数组b中存放数据的起始偏移位置;len指定读取的最大字节数。
其它方法
long skip( long n):在输入流中跳过n个字节,并返回实际跳过的字节数。
int available():返回在不发生阻塞的情况下,可读取的字节数。
void close():关闭输入流,释放和这个流相关的系统资源。
void mark( int readlimit):在输入流的当前位置放置一个标记,如果读取的字节数多于readlimit设置的值,则流忽略这个标记。
void reset():返回到上一个标记。
boolean markSupported():测试当前流是否支持mark和reset方法。如果支持,返回true,否则返回false。
三个基本的写方法
abstract void write( int b):往输出流中写入一个字节。
void write( byte []b):往输出流中写入数组b中的所有字节。
void write( byte []b, int off, int len):往输出流中写入数组b中从偏移量off开始的len个字节的数据。
其它方法
void flush():刷新输出流,强制缓冲区中的输出字节被写出。
void close():关闭输出流,释放和这个流相关的系统资源。
对文件和流的操作容易引发异常,所以必须要用try - catch语句
主要核心代码
首先是新建一个文件
private final StringFILE_NAME = " Myfile01.txt " ;
写文件
FileOutputStreamfos = null ; // 声明一个全局变量
// 注意下面的语句要进行抛异常处理FileNotFoundExceptione,IOExceptione
fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE); // 写流式文件过程的
函数,这里的权限是私有的
Stringtext = entryText.getText().toString(); // 把输入的内容转化为字符串
fos.write(text.getBytes()); // 把转化为字符串的内容转化为字节,然后写入
// 下面语句写在finally里面
fos.flush(); // 把缓存里的内容写入到文件
fos.close(); // 关闭流
读文件
FileInputStreamfis = null ; // 定义一个全局变量
fis = openFileInput(FILE_NAME); // 打开要读取的文件
if (fis.available() == 0 ){ // 判断文件是否为空,为空就直接返回
return ;
}
byte []readBytes = new byte [fis.available()]; // 把文件里的内容转化为字节
while (fis.read(readBytes) != - 1 ){ // 读文件,直到读到最后
}
Stringtext = new String(readBytes); // 把读到的字节转化为字符串
读文件的第二种方法
Stringpath = " /data/data/cn.itcast.file/files/writeable.txt " ; // 得到文件路径
Filefile = new File(path); // 创建一个文件对象
FileInputStreaminStream = new FileInputStream(file); // 读文件
byte []buffer = new byte [ 1024 ]; // 缓存
int len = 0 ;
ByteArrayOutputStreamoutStream = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != - 1 ){ // 直到读到文件结束
outStream.write(buffer, 0 ,len);
}
byte []data = outStream.toByteArray(); // 得到文件的二进制数据
outStream.close();
inStream.close();
Log.i(TAG, new String(data));
这里列举一个例子,主要是把写入的文件读出来显示在TextView中
第一步,修改布局文件main.xml
ViewCode
1 <? xmlversion = " 1.0 " encoding = " utf-8 " ?>
2 < LinearLayoutxmlns:android = " http://schemas.android.com/apk/res/android "
3 android:orientation = " vertical "
4 android:layout_width = " fill_parent "
5 android:layout_height = " fill_parent "
6 >
7 < TextViewandroid:id = " @+id/label "
8 android:layout_width = " fill_parent "
9 android:layout_height = " wrap_content "
10 android:text = " @string/hello "
11 />
12 < EditTextandroid:id = " @+id/entry "
13 android:text = " 输入文件内容 "
14 android:layout_width = " fill_parent "
15 android:layout_height = " wrap_content " >
16 </ EditText >
17 < LinearLayoutandroid:id = " @+id/LinearLayout01 "
18 android:layout_width = " wrap_content "
19 android:layout_height = " wrap_content " >
20 < Buttonandroid:id = " @+id/write "
21 android:text = " 写入文件 "
22 android:layout_width = " wrap_content "
23 android:layout_height = " wrap_content " >
24 </ Button >
25 < Buttonandroid:id = " @+id/read "
26 android:text = " 读取文件 "
27 android:layout_width = " wrap_content "
28 android:layout_height = " wrap_content " >
29 </ Button >
30 </ LinearLayout >
31 < CheckBoxandroid:id = " @+id/append "
32 android:text = " 追加模式 "
33 android:layout_width = " wrap_content "
34 android:layout_height = " wrap_content " >
35 </ CheckBox >
36 < TextViewandroid:id = " @+id/display "
37 android:text = " 文件内容显示区域 "
38 android:layout_width = " fill_parent "
39 android:layout_height = " fill_parent "
40 android:background = " #FFFFFF "
41 android:textColor = " #000000 " >
42 </ TextView >
43 </ LinearLayout >
复制代码
第二步:写入核心代码,
ViewCode
1 package cn.edu.zwu.tel;
2
3 import java.io.FileInputStream;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import android.app.Activity;
8 import android.content.Context;
9 import android.os.Bundle;
10 import android.view.View;
11 import android.view.View.OnClickListener;
12 import android.widget.Button;
13 import android.widget.CheckBox;
14 import android.widget.EditText;
15 import android.widget.TextView;
16
17 public class FileSaveTest01Activity extends Activity{
18
19 private final StringFILE_NAME = " Myfile01.txt " ;
20 private TextViewlabelView;
21 private TextViewdisplayView;
22 private CheckBoxappendBox;
23 private EditTextentryText;
24 @Override
25 public void onCreate(BundlesavedInstanceState){
26 super .onCreate(savedInstanceState);
27 setContentView(R.layout.main);
28
29 labelView = (TextView)findViewById(R.id.label);
30 displayView = (TextView)findViewById(R.id.display);
31 appendBox = (CheckBox)findViewById(R.id.append);
32 entryText = (EditText)findViewById(R.id.entry);
33 ButtonwriteButton = (Button)findViewById(R.id.write);
34 ButtonreadButton = (Button)findViewById(R.id.read);
35 writeButton.setOnClickListener(writeButtonListener);
36 readButton.setOnClickListener(readButtonListener);
37 entryText.selectAll();
38 entryText.findFocus();
39 }
40
41
42 OnClickListenerwriteButtonListener = new OnClickListener(){
43 @Override
44 public void onClick(Viewv){
45 FileOutputStreamfos = null ;
46 try {
47 if (appendBox.isChecked()){
48 fos = openFileOutput(FILE_NAME,Context.MODE_APPEND);
49 }
50 else {
51 fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE);
52 }
53
54 Stringtext = entryText.getText().toString();
55 fos.write(text.getBytes());
56 labelView.setText( " 文件写入成功,写入长度: " + text.length());
57 entryText.setText( "" );
58 } catch (FileNotFoundExceptione){
59 e.printStackTrace();
60 }
61 catch (IOExceptione){
62 e.printStackTrace();
63 }
64 finally {
65 if (fos != null ){
66 try {
67 fos.flush();
68 fos.close();
69 } catch (IOExceptione){
70 e.printStackTrace();
71 }
72 }
73 }
74 }
75 };
76
77 OnClickListenerreadButtonListener = new OnClickListener(){
78 @Override
79 public void onClick(Viewv){
80 displayView.setText( "" );
81 FileInputStreamfis = null ;
82 try {
83 fis = openFileInput(FILE_NAME);
84 if (fis.available() == 0 ){
85 return ;
86 }
87 byte []readBytes = new byte [fis.available()];
88 while (fis.read(readBytes) != - 1 ){
89 }
90 Stringtext = new String(readBytes);
91 displayView.setText(text);
92 labelView.setText( " 文件读取成功,文件长度: " + text.length());
93 } catch (FileNotFoundExceptione){
94 e.printStackTrace();
95 }
96 catch (IOExceptione){
97 e.printStackTrace();
98 }
99
100 }
101 };
102
103 }
复制代码
效果图:
Android文件管理方法
Android使用的是基于Linux的文件系统,对于文件的访问和管理是通过权限设置来限制的.
在Linux系统中,文件权限分别描述了创建者、同组用户和其他用户对文件的操作限制。
x表示可执行,r表示可读,w表示可写,d表示目录, - 表示普通文件。
产生这样的文件权限与程序人员设定的
Android存储文件的类型
(内部存储)程序开发人员可以建立和访问程序自身的私有文件;
(资源存储)可以访问保存在资源目录中的原始文件和XML文件;
(外部存储)可以在SD卡等外部存储设备中保存文件
Android系统允许应用程序创建仅能够自身访问的私有文件,文件保存在设备的内部存储器上,在Linux系统下的 / data / data /< package name >/ files目录中
Android系统不仅支持标准Java的IO类和方法,还提供了能够简化读写流式文件过程的函数
FileOutputStreamopenFileOutput(Stringfilename int mode)
FileInputStreamopenFileInput(Stringfilename)
参数文件不允许包含描述路径的斜杠(其存储位置固定)
访问模式:
MODE_PRIVATE私有模式,缺陷模式,文件仅能够被文件创建程序访问,或具有相同UID的程序访问。
MODE_APPEND追加模式,如果文件已经存在,则在文件的结尾处添加新数据。
MODE_WORLD_READABLE全局读模式,允许任何程序读取私有文件。
MODE_WORLD_WRITEABLE全局写模式,允许任何程序写入私有文件。
三个基本的读方法
abstract int read():读取一个字节数据,并返回读到的数据,如果返回 - 1 ,表示读到了输入流的末尾。
int read( byte []b):将数据读入一个字节数组,同时返回实际读取的字节数。如果返回 - 1 ,表示读到了输入流的末尾。
int read( byte []b, int off, int len):将数据读入一个字节数组,同时返回实际读取的字节数。如果返回 - 1 ,表示读到了输入流的末尾。off指定在数组b中存放数据的起始偏移位置;len指定读取的最大字节数。
其它方法
long skip( long n):在输入流中跳过n个字节,并返回实际跳过的字节数。
int available():返回在不发生阻塞的情况下,可读取的字节数。
void close():关闭输入流,释放和这个流相关的系统资源。
void mark( int readlimit):在输入流的当前位置放置一个标记,如果读取的字节数多于readlimit设置的值,则流忽略这个标记。
void reset():返回到上一个标记。
boolean markSupported():测试当前流是否支持mark和reset方法。如果支持,返回true,否则返回false。
三个基本的写方法
abstract void write( int b):往输出流中写入一个字节。
void write( byte []b):往输出流中写入数组b中的所有字节。
void write( byte []b, int off, int len):往输出流中写入数组b中从偏移量off开始的len个字节的数据。
其它方法
void flush():刷新输出流,强制缓冲区中的输出字节被写出。
void close():关闭输出流,释放和这个流相关的系统资源。
对文件和流的操作容易引发异常,所以必须要用try - catch语句
主要核心代码
首先是新建一个文件
private final StringFILE_NAME = " Myfile01.txt " ;
写文件
FileOutputStreamfos = null ; // 声明一个全局变量
// 注意下面的语句要进行抛异常处理FileNotFoundExceptione,IOExceptione
fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE); // 写流式文件过程的
函数,这里的权限是私有的
Stringtext = entryText.getText().toString(); // 把输入的内容转化为字符串
fos.write(text.getBytes()); // 把转化为字符串的内容转化为字节,然后写入
// 下面语句写在finally里面
fos.flush(); // 把缓存里的内容写入到文件
fos.close(); // 关闭流
读文件
FileInputStreamfis = null ; // 定义一个全局变量
fis = openFileInput(FILE_NAME); // 打开要读取的文件
if (fis.available() == 0 ){ // 判断文件是否为空,为空就直接返回
return ;
}
byte []readBytes = new byte [fis.available()]; // 把文件里的内容转化为字节
while (fis.read(readBytes) != - 1 ){ // 读文件,直到读到最后
}
Stringtext = new String(readBytes); // 把读到的字节转化为字符串
读文件的第二种方法
Stringpath = " /data/data/cn.itcast.file/files/writeable.txt " ; // 得到文件路径
Filefile = new File(path); // 创建一个文件对象
FileInputStreaminStream = new FileInputStream(file); // 读文件
byte []buffer = new byte [ 1024 ]; // 缓存
int len = 0 ;
ByteArrayOutputStreamoutStream = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != - 1 ){ // 直到读到文件结束
outStream.write(buffer, 0 ,len);
}
byte []data = outStream.toByteArray(); // 得到文件的二进制数据
outStream.close();
inStream.close();
Log.i(TAG, new String(data));
这里列举一个例子,主要是把写入的文件读出来显示在TextView中
第一步,修改布局文件main.xml
ViewCode
1 <? xmlversion = " 1.0 " encoding = " utf-8 " ?>
2 < LinearLayoutxmlns:android = " http://schemas.android.com/apk/res/android "
3 android:orientation = " vertical "
4 android:layout_width = " fill_parent "
5 android:layout_height = " fill_parent "
6 >
7 < TextViewandroid:id = " @+id/label "
8 android:layout_width = " fill_parent "
9 android:layout_height = " wrap_content "
10 android:text = " @string/hello "
11 />
12 < EditTextandroid:id = " @+id/entry "
13 android:text = " 输入文件内容 "
14 android:layout_width = " fill_parent "
15 android:layout_height = " wrap_content " >
16 </ EditText >
17 < LinearLayoutandroid:id = " @+id/LinearLayout01 "
18 android:layout_width = " wrap_content "
19 android:layout_height = " wrap_content " >
20 < Buttonandroid:id = " @+id/write "
21 android:text = " 写入文件 "
22 android:layout_width = " wrap_content "
23 android:layout_height = " wrap_content " >
24 </ Button >
25 < Buttonandroid:id = " @+id/read "
26 android:text = " 读取文件 "
27 android:layout_width = " wrap_content "
28 android:layout_height = " wrap_content " >
29 </ Button >
30 </ LinearLayout >
31 < CheckBoxandroid:id = " @+id/append "
32 android:text = " 追加模式 "
33 android:layout_width = " wrap_content "
34 android:layout_height = " wrap_content " >
35 </ CheckBox >
36 < TextViewandroid:id = " @+id/display "
37 android:text = " 文件内容显示区域 "
38 android:layout_width = " fill_parent "
39 android:layout_height = " fill_parent "
40 android:background = " #FFFFFF "
41 android:textColor = " #000000 " >
42 </ TextView >
43 </ LinearLayout >
复制代码
第二步:写入核心代码,
ViewCode
1 package cn.edu.zwu.tel;
2
3 import java.io.FileInputStream;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import android.app.Activity;
8 import android.content.Context;
9 import android.os.Bundle;
10 import android.view.View;
11 import android.view.View.OnClickListener;
12 import android.widget.Button;
13 import android.widget.CheckBox;
14 import android.widget.EditText;
15 import android.widget.TextView;
16
17 public class FileSaveTest01Activity extends Activity{
18
19 private final StringFILE_NAME = " Myfile01.txt " ;
20 private TextViewlabelView;
21 private TextViewdisplayView;
22 private CheckBoxappendBox;
23 private EditTextentryText;
24 @Override
25 public void onCreate(BundlesavedInstanceState){
26 super .onCreate(savedInstanceState);
27 setContentView(R.layout.main);
28
29 labelView = (TextView)findViewById(R.id.label);
30 displayView = (TextView)findViewById(R.id.display);
31 appendBox = (CheckBox)findViewById(R.id.append);
32 entryText = (EditText)findViewById(R.id.entry);
33 ButtonwriteButton = (Button)findViewById(R.id.write);
34 ButtonreadButton = (Button)findViewById(R.id.read);
35 writeButton.setOnClickListener(writeButtonListener);
36 readButton.setOnClickListener(readButtonListener);
37 entryText.selectAll();
38 entryText.findFocus();
39 }
40
41
42 OnClickListenerwriteButtonListener = new OnClickListener(){
43 @Override
44 public void onClick(Viewv){
45 FileOutputStreamfos = null ;
46 try {
47 if (appendBox.isChecked()){
48 fos = openFileOutput(FILE_NAME,Context.MODE_APPEND);
49 }
50 else {
51 fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE);
52 }
53
54 Stringtext = entryText.getText().toString();
55 fos.write(text.getBytes());
56 labelView.setText( " 文件写入成功,写入长度: " + text.length());
57 entryText.setText( "" );
58 } catch (FileNotFoundExceptione){
59 e.printStackTrace();
60 }
61 catch (IOExceptione){
62 e.printStackTrace();
63 }
64 finally {
65 if (fos != null ){
66 try {
67 fos.flush();
68 fos.close();
69 } catch (IOExceptione){
70 e.printStackTrace();
71 }
72 }
73 }
74 }
75 };
76
77 OnClickListenerreadButtonListener = new OnClickListener(){
78 @Override
79 public void onClick(Viewv){
80 displayView.setText( "" );
81 FileInputStreamfis = null ;
82 try {
83 fis = openFileInput(FILE_NAME);
84 if (fis.available() == 0 ){
85 return ;
86 }
87 byte []readBytes = new byte [fis.available()];
88 while (fis.read(readBytes) != - 1 ){
89 }
90 Stringtext = new String(readBytes);
91 displayView.setText(text);
92 labelView.setText( " 文件读取成功,文件长度: " + text.length());
93 } catch (FileNotFoundExceptione){
94 e.printStackTrace();
95 }
96 catch (IOExceptione){
97 e.printStackTrace();
98 }
99
100 }
101 };
102
103 }
复制代码
效果图:
更多相关文章
- Android(安卓)源代码结构
- Android中系统自带数据库文件中的多表联合查询疑问
- Android遇到java.lang.RuntimeException: Binary XML file line
- Android(安卓)Gradle 看这一篇就够了
- Android2.2添加busybox 支持——基于Android(安卓)Bionic库
- Android(安卓)自定义水平进度条的圆角进度
- dex替换方式实现热修复
- 基于Android(安卓)5.1系统的nfc读卡驱动和上层的调试记录,nfc移植
- Ionic cordova Android定位相关问题的小记录