Android存储——SD卡或者文件存储实现
Android实现SD卡和实现内存文件存储的做法基本是一样的。只是取得文件路径的方法不一样,基本上跟java的文件操作是一致的,下面是程序的代码。配置取的位置和实现有所不同,其他是一样的,下面是代码:
main.xml:
[html]
<?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">
<EditText android:id="@+id/edit1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="4"/>
<Button android:id="@+id/write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/write"/>
<EditText android:id="@+id/edit2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:cursorVisible="false"
android:lines="4"/>
<Button android:id="@+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/read"/>
</LinearLayout>
在AndroidManifest清单文件中要对SD卡读取进行支持。代码如下:
[html]
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在String.xml中添加两个内容:
[html]
<string name="read">读取</string>
lt;string name="write">写入</string>
下面是文件实现的代码:
[java]
package cn.jason.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class FileTestActivity extends Activity {
final String FILE = "jason.bin";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
final EditText edit1 = (EditText) findViewById(R.id.edit1);
final EditText edit2 = (EditText) findViewById(R.id.edit2);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
write(edit1.getText().toString());
edit1.setText("");
}
});
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
edit2.setText(read());
}
});
}
private String read() {
try {
FileInputStream fis = openFileInput(FILE);
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder("");
while ((hasRead = fis.read(buffer)) > 0) {
sb.append(new String(buffer, 0, hasRead));
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void write(String content)
{
try
{
// 以追加模式打开文件输出流
FileOutputStream fos = openFileOutput(FILE, MODE_APPEND);
// 将FileOutputStream包装成PrintStream
PrintStream ps = new PrintStream(fos);
// 输出文件内容 www.2ct
补充:移动开发 , Android ,