1,创建文件夹
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
String sdDir = Environment.getExternalStorageDirectory()
.getAbsolutePath();
sdDir += File.separator + "command";
File newFile = new File(sdDir);
if (!newFile.exists()) {
newFile.mkdir();
}
}
2.创建文件
File file = new File(sdDir + File.separator + "sharedMemory.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
// TODO: handle exception
}
}
3,写文件
FileOutputStream out = null;
try {
out = new FileOutputStream(file,true);//true表示在文件末尾添加
byte[] data = new byte[1024];
data[0] = 'k';//for test
data[1] = 'k';
out.write(data);
out.close();
} catch (Exception e) {
// TODO: handle exception
}
4,读文件
try {
byte Buffer[] = new byte[1024];
FileInputStream in = new FileInputStream(file);
int len = in.read(Buffer);// 如果要读完请使用while循环
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(Buffer, 0, len);
String string = new String(outputStream.toByteArray());
Log.i(TAG, "read some:" + string);
} catch (Exception e) {
// TODO: handle exception
}