本文实例讲述了android实现把文件存放在sdcard的方法。分享给大家供大家参考。具体如下:
使用activity的openfileoutput()方法保存文件,文件是存放在手机空间上,一般手机的存储空间不是很大,存放些小文件还行,如果要存放像视频这样的大文件,是不可行的。对于像视频这样的大文件,我们可以把它存放在sdcard。 sdcard是干什么的?你可以把它看作是移动硬盘或u盘。
在模拟器中使用sdcard,你需要先创建一张sdcard卡(当然不是真的sdcard,只是镜像文件)。创建sdcard可以在eclipse创建模拟器时随同创建,也可以使用dos命令进行创建,如下:在dos窗口中进入android sdk安装路径的tools目录,输入以下命令创建一张容量为2g的sdcard,文件后缀可以随便取,建议使用.img:
mksdcard 2048m d:\androidtool\sdcard.img
注意:在程序中访问sdcard,你需要申请访问sdcard的权限。
在androidmanifest.xml中加入访问sdcard的权限如下:
<!-- 在sdcard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.mount_unmount_filesystems"/>
<!-- 往sdcard写入数据权限 -->
<uses-permission android:name="android.permission.write_external_storage"/>
要往sdcard存放文件,程序必须先判断手机是否装有sdcard,并且可以进行读写。
注意:访问sdcard必须在androidmanifest.xml中加入访问sdcard的权限
1
2
3
4
5
6
7
|
if (environment.getexternalstoragestate().equals(environment.media_mounted)){
file sdcarddir = environment.getexternalstoragedirectory(); //获取sdcard目录
file savefile = new file(sdcarddir, "ljq.txt" );
fileoutputstream outstream = new fileoutputstream(savefile);
outstream.write( "abc" .getbytes());
outstream.close();
}
|
environment.getexternalstoragestate()方法用于获取sdcard的状态,如果手机装有sdcard,并且可以进行读写,
那么方法返回的状态等于environment.media_mounted。
environment.getexternalstoragedirectory()方法用于获取sdcard的目录,当然要获取sdcard的目录,你也可以这样写:
file sdcarddir = new file("/mnt/sdcard"); //获取sdcard目录
file savefile = new file(sdcarddir, "ljq.txt");
//上面两句代码可以合成一句: file savefile = new file("/mnt/sdcard/ljq.txt");
fileoutputstream outstream = new fileoutputstream(savefile);
outstream.write("abc".getbytes());
outstream.close();
案例
main.xml布局文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
<?xml version= "1.0" encoding= "utf-8" ?>
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
>
<!-- 相对布局 -->
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
<textview android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:text= "@string/filename"
android:id= "@+id/filenamelable" />
<edittext android:layout_width= "250px"
android:layout_height= "wrap_content"
android:layout_torightof= "@id/filenamelable"
android:layout_aligntop= "@id/filenamelable"
android:layout_marginleft= "10px"
android:text= "ljq.txt"
android:id= "@+id/filename" />
</relativelayout>
<textview android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "@string/content" />
<edittext android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:minlines= "3"
android:id= "@+id/content" />
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
<button android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:text= "@string/button"
android:id= "@+id/button" />
<button android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_torightof= "@id/button"
android:layout_aligntop= "@id/button"
android:layout_marginleft= "10px"
android:minlines= "3"
android:text= "@string/readbutton"
android:id= "@+id/readbutton" />
</relativelayout>
<textview android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:id= "@+id/resultview" />
</linearlayout>
|
strings.xml:
1
2
3
4
5
6
7
8
9
10
11
|
<?xml version= "1.0" encoding= "utf-8" ?>
<resources>
<string name= "hello" >hello world, fileactivity!</string>
<string name= "app_name" >数据保存</string>
<string name= "filename" >文件名称</string>
<string name= "content" >文件内容</string>
<string name= "button" >保存</string>
<string name= "readbutton" >读取内容</string>
<string name= "error" >保存失败</string>
<string name= "success" >保存成功</string>
</resources>
|
fileservice工具类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package com.ljq.service;
import java.io.bytearrayoutputstream;
import java.io.inputstream;
import java.io.outputstream;
public class fileservice {
/**
* 保存数据
*
* @param outputstream
* @param content
* @throws exception
*/
public static void save(outputstream outputstream, string content) throws exception {
outputstream.write(content.getbytes());
outputstream.close();
}
/**
* 读取数据
*
* @param inputstream
* @return
* @throws exception
*/
public static string read(inputstream inputstream) throws exception {
bytearrayoutputstream bytearrayoutputstream = new bytearrayoutputstream(); // 往内存写数据
byte [] buffer = new byte [ 1024 ]; // 缓冲区
int len = - 1 ;
while ((len = inputstream.read(buffer)) != - 1 ) {
bytearrayoutputstream.write(buffer, 0 , len);
}
byte [] data = bytearrayoutputstream.tobytearray(); // 存储数据
bytearrayoutputstream.close();
inputstream.close();
return new string(data);
}
}
|
sdcardactivity类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package com.ljq.sdcard;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.inputstream;
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.textview;
import android.widget.toast;
import com.ljq.service.fileservice;
public class sdcardactivity extends activity {
private final string tag = "fileactivity" ;
private edittext filenametext;
private textview resultview;
private edittext contenttext;
@override
public void oncreate(bundle savedinstancestate) {
super .oncreate(savedinstancestate);
setcontentview(r.layout.main);
filenametext = (edittext) this .findviewbyid(r.id.filename);
contenttext = (edittext) this .findviewbyid(r.id.content);
resultview = (textview) this .findviewbyid(r.id.resultview);
button button = (button) this .findviewbyid(r.id.button);
button.setonclicklistener(listener);
button readbutton = (button) this .findviewbyid(r.id.readbutton);
readbutton.setonclicklistener(listener);
}
private view.onclicklistener listener = new view.onclicklistener() {
public void onclick(view v) {
button button = (button) v;
string filename = filenametext.gettext().tostring();
// environment.getexternalstoragedirectory()等价于new file("/sdcard")---->获取sdcard目录
//获取sdcard目录
//file file = new file("/sdcard" + filename);
file file = new file(environment.getexternalstoragedirectory(), filename);
switch (button.getid()) {
case r.id.button:
int resid = r.string.success; // 默认成功
string content = contenttext.gettext().tostring();
//sdcard存在并且可以读写
if (environment.getexternalstoragestate().equals(environment.media_mounted)) {
try {
fileoutputstream fileoutputstream = new fileoutputstream(file);
fileservice.save(fileoutputstream, content);
} catch (exception e) {
log.e(tag, e.tostring());
resid = r.string.error;
}
toast.maketext(sdcardactivity. this , resid, toast.length_long).show();
} else {
toast.maketext(sdcardactivity. this , "sdcard不存在或写保护" , toast.length_long).show();
}
break ;
case r.id.readbutton:
try {
inputstream inputstream= new fileinputstream(file);
string text = fileservice.read(inputstream);
resultview.settext(text);
} catch (exception e) {
log.e(tag, e.tostring());
toast.maketext(sdcardactivity. this , "读取失败" , toast.length_long).show();
}
break ;
}
}
};
}
|
清单文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
package = "com.ljq.sdcard" android:versioncode= "1"
android:versionname= "1.0" >
<application android:icon= "@drawable/icon"
android:label= "@string/app_name" >
<activity android:name= ".sdcardactivity"
android:label= "@string/app_name" >
<intent-filter>
<action android:name= "android.intent.action.main" />
<category
android:name= "android.intent.category.launcher" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minsdkversion= "7" />
<!-- 在sdcard中创建与删除文件权限 -->
<uses-permission
android:name= "android.permission.mount_unmount_filesystems" />
<!-- 往sdcard写入数据权限 -->
<uses-permission android:name= "android.permission.write_external_storage" />
</manifest>
|
运行结果:
希望本文所述对大家的android程序设计有所帮助。