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

本文介绍了如何在Android设备的SD卡上创建文件夹和文件,并进行读写操作,包括两个主要步骤:1)详细说明了创建文件夹的流程;2)阐述了创建文件的方法,为Android应用开发提供基础支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
			}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值