WEB开发网
开发学院手机开发Android 开发 Android 文件存储详解(SD卡或手机内存存储) 阅读

Android 文件存储详解(SD卡或手机内存存储)

 2012-06-10 07:48:59 来源:WEB开发网   
核心提示: package gongzibai.co.cc;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.PrintStream;import android.app.Activity;import android.os

 package gongzibai.co.cc;

import java.io.FileInputStream;
import java.io.FileOutputStream;
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 Ex6Activity extends Activity {
/** Called when the activity is first created. */
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) {
// TODO Auto-generated method stub
write(edit1.getText().toString());
edit1.setText("");

}

private void write(String string) {
// TODO Auto-generated method stub
try {
FileOutputStream fos = openFileOutput(FILE, MODE_APPEND);
PrintStream ps = new PrintStream(fos);
ps.println(string);
ps.close();

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

}
});

read.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
edit2.setText(read());

}

private CharSequence read() {
// TODO Auto-generated method stub
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 (Exception e) {
// TODO: handle exception
e.printStackTrace();

}
return null;
}
});

}
}

----------------创建文件到SD卡中

File file = new File("/sdcard/json.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

-------------------存储在SD卡中数据

package gongzibai.co.cc;

import java.io.File;
import java.io.FileInputStream;

1 2  下一页

Tags:Android 文件 存储

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接