android SD卡创建文件夹,文件并读写

来源:互联网 发布:安全家庭是什么软件 编辑:程序博客网 时间:2024/05/18 02:58

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}


0 0