API Level 8から使えるようになったContext.getExternalFilesDirは外部ストレージのパスに、パッケージ名を追加して、さらにディレクトリが存在しなければ作成もしておいてくれるという、今までEnvironment.getExternalStorageDirectoryを使って書いていた部分を短くできる便利なメソッドです。
で、このメソッドがnullを返す場合、大抵はパーミッション不足です。
AndroidManifest.xmlに外部ストレージへの書き込みを許可する行を追加しましょう。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
何が問題かって、このメソッドがパーミッションのExceptionを投げてくれずに、nullしか返さないことです。
ちなみにこのメソッドを使ってファイルをコピーするプログラムはこんな感じになりました。
File dst = new File(mContext.getExternalFilesDir(null), "dst.txt");
// dst = "/mnt/sdcard/Android/data/com.sample/files/dst.txt"
FileChannel srcChannel = null;
FileChannel destChannel = null;
try {
// ファイルのコピー
if (dst.exists()) {
dst.delete();
}
dst.createNewFile();
FileInputStream in = mContext.openFileInput("src.txt");
FileOutputStream out = new FileOutputStream(dst, false);
srcChannel = in.getChannel();
destChannel = out.getChannel();
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (srcChannel != null) {
try {
srcChannel.close();
} catch (IOException e) {
}
}
if (destChannel != null) {
try {
destChannel.close();
} catch (IOException e) {
}
}
}

HOMMA Teppei

