質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
ストレージ

ストレージとは、データを長期で保管・保存しておくための記憶装置。ハードディスクやDVD、CDなどが主なストレージとして挙げられます。PCでは作成データの他、OSやアプリケーションがインストールされています。

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

保存

保存(save)とは、特定のファイルを、ハードディスク等の外部記憶装置に記録する行為を指します。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

Q&A

解決済

1回答

2098閲覧

Androidアプリで内部ストレージに作成したファイルを保存したい

sszkks

総合スコア15

ストレージ

ストレージとは、データを長期で保管・保存しておくための記憶装置。ハードディスクやDVD、CDなどが主なストレージとして挙げられます。PCでは作成データの他、OSやアプリケーションがインストールされています。

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

保存

保存(save)とは、特定のファイルを、ハードディスク等の外部記憶装置に記録する行為を指します。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

0グッド

1クリップ

投稿2019/11/18 16:25

編集2019/11/18 23:30

行いたいこと

Androidアプリ内でpdfファイルを作成し、内部ストレージに保存したい

開発環境

AndroidStudio 3.5.1

minSdkVersion 19
targetSdkVersion 29

参考にしたサイト

内部ストレージへの保存

pdfの作成

状況

Saveボタンを押下するも正しく保存されず下記のエラーが出力される

java.io.FileNotFoundException: file:/data/user/0/com.example.internalstragetest/files (No such file or directory)

ソースコード

Kotlin

1package com.example.internalstragetest 2 3import android.content.Context 4import android.graphics.Color 5import android.graphics.Paint 6import android.graphics.pdf.PdfDocument 7import android.os.Bundle 8import android.os.SystemClock 9import android.text.TextPaint 10import android.util.Log 11import android.view.View 12import androidx.appcompat.app.AppCompatActivity 13import kotlinx.android.synthetic.main.activity_main.* 14import java.io.* 15import android.widget.Toast 16import androidx.core.app.ComponentActivity.ExtraData 17import androidx.core.content.ContextCompat.getSystemService 18import android.icu.lang.UCharacter.GraphemeClusterBreak.T 19 20 21 22 23class MainActivity : AppCompatActivity() { 24 25 private val fileName = "testfile.txt" 26 27 override fun onCreate(savedInstanceState: Bundle?) { 28 super.onCreate(savedInstanceState) 29 setContentView(R.layout.activity_main) 30 31 // Save file 32 button_save.setOnClickListener { 33 createPdf() 34// // get string contents of EditText 35// val contents = edit_text.text.toString() 36// 37// if (contents.isNotEmpty()) { 38// saveFile(fileName, contents) 39// text_view.text = getString(R.string.saved) 40// } else { 41// text_view.text = getString(R.string.no_text) 42// } 43 } 44 45 // Read file 46 button_read.setOnClickListener { 47 val str = readFiles(fileName) 48 if (str != null) { 49 text_view.text = str 50 } else { 51 text_view.text = getString(R.string.read_error) 52 } 53 } 54 } 55 56 57 private fun saveFile(file: String, str: String) { 58 59// applicationContext.openFileOutput(file, Context.MODE_PRIVATE).use { 60// it.write(str.toByteArray()) 61// } 62 applicationContext.openFileOutput(file, Context.MODE_PRIVATE).use { 63 64 it.write(str.toByteArray()) 65 } 66 67 68 } 69 70 private fun readFiles(file: String): String? { 71 72 // to check whether file exists or not 73 val readFile = File(applicationContext.filesDir, file) 74 75 if (!readFile.exists()) { 76 Log.d("debug", "No file exists") 77 return null 78 } else { 79 return readFile.bufferedReader().use(BufferedReader::readText) 80 } 81 } 82 83 private fun createPdf() { 84 // create a new document 85 val document = PdfDocument() 86 87 // crate a page description 88 var pageInfo: PdfDocument.PageInfo = PdfDocument.PageInfo.Builder(100, 100, 1).create() 89 90 // start a page 91 var page: PdfDocument.Page = document.startPage(pageInfo) 92 93 var canvas = page.canvas 94 95 var paint = Paint() 96 paint.color = Color.RED 97 98 canvas.drawCircle(50f, 50f, 30f, paint) 99 100 // finish the page 101 document.finishPage(page) 102 103 // Create Page 2 104 pageInfo = PdfDocument.PageInfo.Builder(500, 500, 2).create() 105 page = document.startPage(pageInfo) 106 canvas = page.canvas 107 paint = Paint() 108 paint.color = Color.BLUE 109 canvas.drawCircle(200f, 200f, 100f, paint) 110 document.finishPage(page) 111 112 // write the document content 113 val targetPdf = "test.pdf" 114// val filePath = File(applicationContext.filesDir.toURI().toString()+"/") 115 val filePath = File(applicationContext.filesDir.toURI().toString()) 116// applicationContext.openFileOutput(filePath.toString(), Context.MODE_PRIVATE).use { 117// it.write(str.toByteArray()) 118 try { 119 document.writeTo(FileOutputStream(filePath)) 120 Toast.makeText(this, "Done", Toast.LENGTH_LONG).show() 121 } catch (e: IOException) { 122 Log.d("DEBUG","@@@${e}") 123 Toast.makeText(this, "Something wrong: $e", 124 Toast.LENGTH_LONG).show() 125 } 126 127// } 128 129 // close the document 130 document.close() 131 } 132}

xml

1<?xml version="1.0" encoding="utf-8"?> 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 android:gravity="center_horizontal" 8 android:background="#dfe" 9 tools:context=".MainActivity"> 10 11 <EditText 12 android:id="@+id/edit_text" 13 android:hint="@string/hint" 14 android:layout_margin="50dp" 15 android:textSize="30sp" 16 android:background="#fff" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" /> 19 20 <LinearLayout 21 android:orientation="horizontal" 22 android:gravity="center" 23 android:layout_width="match_parent" 24 android:layout_height="wrap_content"> 25 26 <Button 27 android:id="@+id/button_save" 28 android:text="@string/save_file" 29 android:layout_margin="20dp" 30 android:textSize="20sp" 31 android:layout_width="wrap_content" 32 android:layout_height="wrap_content" /> 33 34 <Button 35 android:id="@+id/button_read" 36 android:text="@string/read_file" 37 android:textSize="20sp" 38 android:layout_margin="20dp" 39 android:layout_width="wrap_content" 40 android:layout_height="wrap_content" /> 41 </LinearLayout> 42 43 <TextView 44 android:id="@+id/text_view" 45 android:textSize="30sp" 46 android:textColor="#000" 47 android:layout_margin="20sp" 48 android:layout_width="wrap_content" 49 android:layout_height="wrap_content" /> 50 51</LinearLayout>

追記

try-catchを外してエラーを出力させました。
エラーとなっているのはdocument.writeTo(FileOutputStream(filePath))です。

2019-11-19 08:20:30.887 13113-13113/com.example.internalstragetest E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.internalstragetest, PID: 13113 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)  Caused by: java.io.FileNotFoundException: file:/data/user/0/com.example.internalstragetest/files (No such file or directory) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:221) at java.io.FileOutputStream.<init>(FileOutputStream.java:169) at com.example.internalstragetest.MainActivity.createPdf(MainActivity.kt:119) at com.example.internalstragetest.MainActivity.access$createPdf(MainActivity.kt:23) at com.example.internalstragetest.MainActivity$onCreate$1.onClick(MainActivity.kt:33) at android.view.View.performClick(View.java:5637) at android.view.View$PerformClick.run(View.java:22433) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6173) at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

FilePathにtargetPDFを追記した場合

FilePathをフォルダ名だけでなく、フォルダ名+ファイル名にした場合は下記のエラーが出力されます。

2019-11-19 08:25:09.314 13579-13579/com.example.internalstragetest E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.internalstragetest, PID: 13579 java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)  Caused by: java.io.FileNotFoundException: file:/data/user/0/com.example.internalstragetest/files/test.pdf (No such file or directory) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:221) at java.io.FileOutputStream.<init>(FileOutputStream.java:169) at

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2019/11/18 19:23

例外はその一文だけでしょうか. 通常はその下にずらずらと発生個所が表示されているかと思います. それらを全て載せて頂けますか. そして, 発生行はどこでしょうか.
sszkks

2019/11/21 16:18

ご指摘いただいた内容を踏まえ追記させていただきました。 恐れ入りますがご助言等いただけますと幸いです。
guest

回答1

0

ベストアンサー

val targetPdf = "test.pdf" val filePath = File(applicationContext.filesDir.toURI().toString()) try { document.writeTo(FileOutputStream(filePath))

targetPdf が使用されておらず, filePath はフォルダ名までなのではないでしょうか.


見落としていました.
File に渡すのはパスであってURIではありません.
targetPdf をどう追加して試されたのか分かりませんが, 私が引用した状態から

val filePath = File(applicationContext.filesDir.toURI().toString())

val filePath = File(applicationContext.filesDir, targetPdf)

としてみてください.

投稿2019/11/18 19:26

編集2019/11/22 17:18
jimbe

総合スコア12646

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

sszkks

2019/11/22 17:15

いただいた内容で試したところ無事に保存することができました。 URIを渡してはいけないのですね… ありがとうございました。
jimbe

2019/11/22 17:21

パスを URI にすると "file:" という部分が付いてしまい, File はそれをフォルダ名と勘違いしてしまいます. なんとなく "file:" が付いているのも見慣れているため, 見落としてしまいました. すいません.
sszkks

2019/11/22 17:23

"file:" がつくことで悪さをされてしまうんですね… 本当に助かりました。ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問