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

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

 2012-06-10 07:48:59 来源:WEB开发网   
核心提示:import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import android.app.Activity;import android.os.Bundle;import android.view.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

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 = "/sdcard/gogo.txt";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File path = new File(FILE);
if (!path.exists())
{
try {
path.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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 {
OutputStream os = new FileOutputStream(FILE,true);
os.write(string.getBytes());
os.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 = new FileInputStream(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;
}
});

}
}

上一页  1 2 

Tags:Android 文件 存储

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