主要的代码:
MainActivity.java
package cn.bzu.fileoperation;
import java.io.IOException;
import cn.bzu.service.FileService;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private FileService fileService;
private Button saveButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileService = new FileService(this);
saveButton = (Button) this.findViewById(R.id.save);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
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();
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
try {
fileService.saveToSDCard(fileName, fileContent);
Toast.makeText(MainActivity.this, R.string.success,
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, R.string.failure,
Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(MainActivity.this, R.string.sdcarderror, Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
FileService.java
package cn.bzu.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
public class FileService {
private Context context;
public FileService(Context context) {
super();
this.context = context;
}
/**
* 保存文件
*/
public void save(String filename, String filecontent) throws IOException {
// 第1个参数是文件的名称,第2个参数是操作模式
FileOutputStream fos = context.openFileOutput(filename,
Context.MODE_WORLD_WRITEABLE + Context.MODE_WORLD_READABLE);
fos.write(filecontent.getBytes());
fos.close();
}
public void saveToSDCard(String filename, String filecontent)
throws IOException {
//绝对路径
//File file = new File("/mnt/sdcard", filename);
System.out.println(Environment.getExternalStorageDirectory());
File file=new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream fos = new FileOutputStream(file);// 创建文件输出流
fos.write(filecontent.getBytes());
fos.close();
}
public String readFile(String filename) throws IOException {
FileInputStream fis = context.openFileInput(filename);
int len = 0;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 往内存中输出数据的
while ((len = fis.read(buffer)) != -1)// 如果数据量很大,第2次读取的数据有可能会把第1次读取的数据给覆盖掉
{
baos.write(buffer, 0, len);
}
byte[] data = baos.toByteArray();// 得到内存中的数据 以二进制存放的
baos.close();
fis.close();
return new String(data);// 根据二进制数据转换成所对应的字符串
}
}
接下来,让我们看一下布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/filename" />
<EditText
android:id="@+id/filename"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/filecontent" />
<EditText
android:id="@+id/filecontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minLines="5" />
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save" />
</LinearLayout>
有一点,最好对、FileService进行一下单元测试:
package cn.bzu.service;
import java.io.IOException;
import android.test.AndroidTestCase;
public class FileServiceTest extends AndroidTestCase {
public void testSave() throws IOException{
FileService fileService=new FileService(getContext());
fileService.save("file1.txt", "使用文件");
}
public void testRead() throws IOException{
FileService fileService=new FileService(getContext());
String content=fileService.readFile("file1.txt");
System.out.println(content);
}
public void testSaveToSDCard()throws IOException{
FileService fileService=new FileService(getContext());
fileService.saveToSDCard("file2.txt", "文件存到sdcard里");
}
}
还有一点很重要,就是设置权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.bzu.fileoperation"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="android.test.runner" />
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 创建文件删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.bzu.fileoperation" >
</instrumentation>
</manifest>
让我们看一下运行图: