<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/name" /> <EditText android:id="@+id/fname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/content" /> <EditText android:id="@+id/fcontent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="text" android:minLines="6" /> <Button android:id="@+id/store" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/store" /> </LinearLayout>
package com.example.service; import java.io.FileOutputStream; import android.content.Context; public class FileService { private Context context; public FileService(Context context) { this.context = context; } public void save(String filename,String content)throws Exception{ FileOutputStream outputStream=context.openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(content.getBytes()); outputStream.close(); } }
package com.example.file; import com.example.service.FileService; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class FileActivity extends Activity { private static final String TAG="FileActivity"; private FileService fileService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file); fileService=new FileService(this); Button button=(Button)this.findViewById(R.id.store); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText filenameText=(EditText)findViewById(R.id.fname); EditText contentText=(EditText)findViewById(R.id.fcontent); String filename=filenameText.getText().toString(); String content=contentText.getText().toString(); try { fileService.save(filename, content); Toast.makeText(FileActivity.this, R.string.success,Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.e(TAG,e.toString()); Toast.makeText(FileActivity.this, R.string.fail,Toast.LENGTH_SHORT).show(); } } }); } }