【Android】データ格納のSDcard

2688 ワード

SDカードは、ユーザーがPCにマウントしたり、読み取り専用に設定したり、SDカードを挿入しなかったりするため、SDカードを使用してデータを格納する前に、SDカードが使用可能かどうかを検出する必要がある場合があります.
1.インベントリファイルへの追加:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

これにより、SDカードの読み書きに権限が与えられます.
2.SDカードの状態を取得して使用する:
Environment.getExternalStorageState()

したがって、書き込み可能かどうかを検出する文は次のとおりです.
Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())

そのため、SDカードにファイルを読み込むコードは以下の通りです.
public String getFileFromSdcard(String filename) {
		FileInputStream fileInputStream = null;
		//   ,     ,     
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				fileInputStream = new FileInputStream(file);
				int len = 0;
				byte[] data = new byte[1024];
				while((len = fileInputStream.read(data))!= -1){
					outputStream.write(data, 0, len);
				}
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if (fileInputStream != null){
					try {
						fileInputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return new String(outputStream.toByteArray());
	}

書き込みファイルコードは次のとおりです.
public boolean saveContentToSdcard(String filename, String content) {
		boolean flag = false;
		FileOutputStream fileOutputStream = null;
		//   sdcrad     
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);

		//   sdcard    
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(content.getBytes());
				flag = true;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (fileOutputStream != null) {
					try {
						fileOutputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return flag;
	}