首先AndroidManifest.xml里要添加对应的权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
其次,就是创建要写数据的文件(文件名自己定义想要的文件名称):
private void createFile() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());
String time = simpleDateFormat.format(date);
try {
file = new File(Environment.getExternalStorageDirectory(),"TestFile"+time+".txt");
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
最后,就是把要写的内容写人对应的文件内了
public void writeTxtToFile(String strcontent) {
// 每次写入时,都换行写
String strContent = strcontent + "\r\n";
try {
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(strContent.getBytes());
raf.close();
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
到这里就完成了,就这么简单!