在android中经常会设计到文件的操作,今天再这里整理一下,供大家参考
package sn.len.savefile.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
public class SaveFileService
{
private Context context=null;
public SaveFileService(Context context)
{
this.context=context;
}
//保存文件到手机
public void saveFile(String fileName,String textContent) throws IOException
{
//实例化fileName文件(输出流)对象
FileOutputStream outStream=context.openFileOutput(fileName, Context.MODE_PRIVATE);
/*
* 操作模式
* Context.MODE_PRIVATE:代表该文件是私有数据,只能被应用本身访问
* Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件
* MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
* MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
* Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE读和写
* Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE+Context.MODE_APPEND读写追加
* */
//写入数据
outStream.write(textContent.getBytes());
//关闭输出流
outStream.close();
}
//从手机读取文件
public String readFile(String fileName) throws IOException
{
//实例化fileName文件(输入流)对象
FileInputStream fis=context.openFileInput(fileName);
//定义byte存储空间
byte[] b=new byte[1024];
//定义读取字节长度
int n=0;
//实例化字节数组流(可以捕获内存缓冲区的数据,转换成字节数组。)
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
//读取数据读到byte中
while((n=fis.read(b))!=-1)
{
//把数据写到byte中
byteArrayOutputStream.write(b);
}
//重缓冲区中拿取二进制数据并转换成字节数组
byte content[]=byteArrayOutputStream.toByteArray();
//返回String
return new String(content);
}
//保存文件到SD卡
public void saveToSdCard(String filename,String content) throws IOException
{
//得到手机默认存储目录。并实例化
File file=new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream fos=new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
}
//重SD卡中读取文件内容
public String readContentForSdcard(String filename) throws IOException
{
//Environment.getExternalStorageDirectory() 得到外部存储目录
File file=new File(Environment.getExternalStorageDirectory(),filename);
FileInputStream sdstream=new FileInputStream(file);
byte b[]=new byte[1024];
int n=0;
ByteArrayOutputStream byteArrayOS=new ByteArrayOutputStream();
while((n=sdstream.read(b))!=-1)
{
byteArrayOS.write(b);
}
byte sdContent[]=byteArrayOS.toByteArray();
return new String(sdContent);
}
}
测试代码
package sn.len.savefile.serviceTest;
import java.io.IOException;
import sn.len.savefile.service.SaveFileService;
import android.test.AndroidTestCase;
import android.util.Log;
public class SaveFileServiceTest extends AndroidTestCase
{
private static final String TAG="textContent";
public void testSaveFile()//测试保存文件
{
try
{
SaveFileService sfs=new SaveFileService(this.getContext());
sfs.saveFile("chinese.txt", "Hello World世界你好");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void testReadFile()//测试读取文件
{
try
{
SaveFileService sfs=new SaveFileService(this.getContext());
String textContent=sfs.readFile("chinese.txt");
Log.i(TAG, textContent);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void testSaveToSdCard()//测试保存到sd card文件
{
SaveFileService sfs=new SaveFileService(this.getContext());
try
{
sfs.saveToSdCard("sdcardfile.txt", "sd card content");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void testReadToSdCard()//测试读取SD卡中的文件
{
SaveFileService sfs=new SaveFileService(this.getContext());
try
{
String readSdContent=sfs.readContentForSdcard("oo.txt");
Log.i(TAG,readSdContent);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Junit保存测试成功
1)选择window-->showView-->Others-->Android-->File Explorer -->OK
2)点击File Explorer标签,选择data-->data-->sn.len.savefile-->files-->chinese-->FileExplorer中的第一个黑色按钮(pull a file from device)导出到桌面
最终运行代码
package sn.len.savefile;
import java.io.IOException;
import sn.len.savefile.service.SaveFileService;
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 SaveFileActivity extends Activity
{
private SaveFileService sfs=null;
private final String TAG="save error";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button save_button=(Button)findViewById(R.id.saveButton);
//实例化业务层(Service)对象
sfs=new SaveFileService(this);
//设置监听
save_button.setOnClickListener
(
new View.OnClickListener()
{
public void onClick(View v)
{
switch(v.getId())
{
case R.id.saveButton:
{
EditText fileName=(EditText)findViewById(R.id.fileName);
EditText fileContent=(EditText)findViewById(R.id.fileContent);
String filename=fileName.getText().toString();
String filecontent=fileContent.getText().toString();
try
{
sfs.saveFile(filename, filecontent);
Toast.makeText(SaveFileActivity.this, R.string.save_success, Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG,e.toString());
Toast.makeText(SaveFileActivity.this, R.string.save_fail, Toast.LENGTH_LONG).show();
}
}
break;
}
}
}
);
}
}