这是一个Android平台的小应用,主要实现了SD卡上文件的读写操作,通过IO流来实现。
MainActivity.java
- package com.landroid.files;
- import com.landroid.files.R;
- import com.landroid.service.FileService;
- 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;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button button = (Button) this.findViewById(R.id.button);
- button.setOnClickListener(new ButtonOnClickListener());
- }
- private final class ButtonOnClickListener implements OnClickListener {
- public void onClick(View v) {
- EditText filenameText = (EditText) findViewById(R.id.filename);
- EditText filecontentText = (EditText) findViewById(R.id.filecontent);
- String filename = filenameText.getText().toString();
- String filecontent = filecontentText.getText().toString();
- FileService service = new FileService(getApplicationContext());
- try {
- service.save(filename, filecontent);
- Toast.makeText(getApplicationContext(), R.string.success, 1).show();
- } catch (Exception e) {
- Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
- e.printStackTrace();
- }
- }
- }
- }
FileService.java
- package com.landroid.service;
- import java.io.ByteArrayOutputStream;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import android.content.Context;
- public class FileService {
- private Context context;
- public FileService(Context context) {
- this.context = context;
- }
- /**
- * 保存文件
- * @param filename 文件名称
- * @param filecontent 文件内容
- */
- public void save(String filename, String filecontent) throws Exception {
- // 私有操作模式:创建出来的文件只能被本应用访问,其它应用无法访问该文件
- // 另外采用私有操作模式创建的文件,写入文件中的内容会覆盖源文件的内容
- FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
- outStream.write(filecontent.getBytes());
- outStream.close();
- }
- /**
- * 读取文件内容
- * @param filename 文件名称
- * @return 文件内容
- * @throws Exception
- */
- public String read(String filename) throws Exception {
- FileInputStream inStream = context.openFileInput(filename);
- byte[] buffer = new byte[1024];
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- int len = 0;
- while((len = inStream.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- }
- byte[] data = outStream.toByteArray();
- new String(data);
- return null;
- }
- }