1. Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
2. Use this class that i implemented
package smswatcher.cn;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
public class SDFileMan {
private String mFolderPath="";
private String mFileName="";
public SDFileMan(String fileName){
File sdCardDir = Environment.getExternalStorageDirectory();
mFileName = fileName;
try
{
mFolderPath = sdCardDir.getCanonicalPath() + "/SMSWatcherLogFolder/";
Initialize();
}catch(Exception e){}
}
private File Initialize() throws IOException
{
File folder = new File(mFolderPath);
if(!folder.exists()){
folder.mkdirs();
}
File file = new File((GetFileFullPath()));
if(!file.exists()){
file.createNewFile();
}
return file;
}
public boolean Exists()
{
File file = new File((GetFileFullPath()));
return file.exists();
}
public boolean saveAppend(String content)
{
try
{
File file = Initialize();
FileOutputStream outputStream = new FileOutputStream(file, true);
outputStream.write(content.getBytes());
outputStream.close();
return true;
}
catch(Exception e)
{
return false;
}
}
public boolean deleteFile()
{
try
{
File file = new File((GetFileFullPath()));
if(file.exists()){
file.delete();
}
return true;
}
catch(Exception e)
{
return false;
}
}
public boolean saveAppendLine(String content)
{
byte[] c = new byte[2];
c[0]=0x0d;
c[1]=0x0a;
String c_string = new String(c);
return saveAppend(content + c_string);
}
public String readFile()
{
try
{
File file = new File(GetFileFullPath());
//获得输入流
FileInputStream inStream = new FileInputStream(file);
//new一个缓冲区
byte[] buffer = new byte[1024];
int len = 0;
//使用ByteArrayOutputStream类来处理输出流
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while( (len = inStream.read(buffer))!= -1)
{
//写入数据
outStream.write(buffer, 0, len);
}
//得到文件的二进制数据
byte[] data = outStream.toByteArray();
//关闭流
outStream.close();
inStream.close();
return new String(data);
}
catch(Exception e)
{
return null;
}
}
public long getFileUpdateTime()
{
File f = new File(GetFileFullPath());
if(f.exists())
return f.lastModified();
else
return -1;
}
private String GetFileFullPath()
{
return mFolderPath + mFileName;
}
}
3. Usage:
SDFileMan mFileMan= new SDFileMan("My.log");
boolean flag = mFileMan.saveAppendLine("哈哈啊哈哈");