0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

【Android】ダウンロードフォルダにファイルを保存

Posted at

概要

ダウンロードフォルダにファイルを保存する方法について解説。

方法

ファイルを保存するメソッド作成

@Throws(IOException::class)
private fun saveFile(context: Context, fileName: String, text: String) {

	//必要に応じて適宜変更
	val extension = "txt"
	val mimeType = "text/plain"
	//val extension = "csv"
	//val mimeType = "text/csv"

	val outputStream: OutputStream? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
		val values = ContentValues()
		values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
		values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
		values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)

		val fileUri = context.contentResolver.insert(MediaStore.Files.getContentUri("external"), values) ?: return
		context.contentResolver.openOutputStream(fileUri)
	} else {
		val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(), "$fileName.$extension")
		FileOutputStream(file)
	}

	outputStream?.write(text.toByteArray())
	outputStream?.close()
}

メソッドを呼び出す

runCatching {
	saveFile(this, "title", "content")
}

参考

関連記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?