Skip to content

Instantly share code, notes, and snippets.

@wasnot
Created June 22, 2015 12:26
Show Gist options
  • Save wasnot/67c977ccc5e028903858 to your computer and use it in GitHub Desktop.
Save wasnot/67c977ccc5e028903858 to your computer and use it in GitHub Desktop.
[Android][Lollipop]Android5.0で可能になったSDカードへの書き込みを試す ref: http://qiita.com/wasnot/items/287d191c7da40f2e6080
// preferenceなどに保存しておいたURiを取り出します。
Uri treeUri = PreferenceUtil.getSharedPreferenceUri();
// SDカードのdocumentを作成します。
DocumentFile sdcard = DocumentFile.fromTreeUri(mContext, treeUri);
// そこからファイルをたどっていく必要があります。
DocumentFile nextDocument = document.findFile("test");
:
// APIを通じてIOStreamを作りたいときはDocumentFileを使うと便利です。
DocumentFile targetDocument = getDocumentFile(file, false);
OutputStream outStream = Application.getAppContext().
getContentResolver().openOutputStream(targetDocument.getUri());
// JavaのFileを扱うように自由に書き込みもできます。
// ただしSAFのAPIを介する必要があります。
// また、一度付与されたuriは保持しておく必要があります。
// Create a new file and write into it
DocumentFile newFile = pickedDir.createFile("text/plain", "My Novel");
try {
OutputStream out = getActivity().getContentResolver().openOutputStream(newFile.getUri());
out.write("A long time ago...".getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment