Home>

I want to create a pdf file in the Android app and save it to the internal storage

Development environment

AndroidStudio 3.5.1

minSdkVersion 19
targetSdkVersion 29

Referenced sites

Save to internal storage

Create PDF

Status

When the Save button is pressed, the following error is output

java.io.FileNotFoundException: file: /data/user/0/com.example.internalstragetest/files (No such file or directory)
Source code
package com.example.internalstragetest
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.os.Bundle
import android.os.SystemClock
import android.text.TextPaint
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main. *
import java.io. *
import android.widget.Toast
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T


class MainActivity: AppCompatActivity () {
    private val fileName = "testfile.txt"
    override fun onCreate (savedInstanceState: Bundle?) {
        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)
        // Save file
        button_save.setOnClickListener {
            createPdf ()
// // get string contents of EditText
// val contents = edit_text.text.toString ()
//
// if (contents.isNotEmpty ()) {
// saveFile (fileName, contents)
// text_view.text = getString (R.string.saved)
//} else {
// text_view.text = getString (R.string.no_text)
//}
        }
        // Read file
        button_read.setOnClickListener {val str = readFiles (fileName)
            if (str! = null) {
                text_view.text = str
            } else {
                text_view.text = getString (R.string.read_error)
            }
        }
    }

    private fun saveFile (file: String, str: String) {
// applicationContext.openFileOutput (file, Context.MODE_PRIVATE) .use {
// it.write (str.toByteArray ())
//}
        applicationContext.openFileOutput (file, Context.MODE_PRIVATE) .use {
            it.write (str.toByteArray ())
        }

    }
    private fun readFiles (file: String): String? {
        // to check whether file exists or not
        val readFile = File (applicationContext.filesDir, file)
        if (! readFile.exists ()) {
            Log.d ("debug", "No file exists")
            return null
        } else {
            return readFile.bufferedReader (). use (BufferedReader :: readText)
        }
    }
    private fun createPdf () {
        // create a new document
        val document = PdfDocument ()
        // crate a page description
        var pageInfo: PdfDocument.PageInfo = PdfDocument.PageInfo.Builder (100, 100, 1) .create ()
        // start a page
        var page: PdfDocument.Page = document.startPage (pageInfo)
        var canvas = page.canvas
        var paint = Paint ()
        paint.color = Color.RED
        canvas.drawCircle (50f, 50f, 30f, paint)
        // finish the page
        document.finishPage (page)
        // Create Page 2
        pageInfo = PdfDocument.PageInfo.Builder (500, 500, 2) .create ()
        page = document.startPage (pageInfo)
        canvas = page.canvas
        paint = Paint ()
        paint.color = Color.BLUE
        canvas.drawCircle (200f, 200f, 100f, paint)
        document.finishPage (page)
        // write the document content
        val targetPdf = "test.pdf"
// val filePath = File (applicationContext.filesDir.toURI (). toString () + "/")val filePath = File (applicationContext.filesDir.toURI (). toString ())
// applicationContext.openFileOutput (filePath.toString (), Context.MODE_PRIVATE) .use {
// it.write (str.toByteArray ())
            try {
                document.writeTo (FileOutputStream (filePath))
                Toast.makeText (this, "Done", Toast.LENGTH_LONG) .show ()
            } catch (e: IOException) {
                Log.d ("DEBUG", "@@@ ${e}")
                Toast.makeText (this, "Something wrong: $e",
                        Toast.LENGTH_LONG) .show ()
            }
//}
        // close the document
        document.close ()
    }
}
<? xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
    xmlns: tools = "http://schemas.android.com/tools"
    android: layout_width = "match_parent"
    android: layout_height = "match_parent"
    android: orientation = "vertical"
    android: gravity = "center_horizontal"
    android: background = "# dfe"
    tools: context = ". MainActivity">
    <EditText
        android: id = "@ + id/edit_text"
        android: hint = "@ string/hint"
        android: layout_margin = "50dp"
        android: textSize = "30sp"
        android: background = "# fff"
        android: layout_width = "wrap_content"
        android: layout_height = "wrap_content" />
    <LinearLayout
        android: orientation = "horizontal"
        android: gravity = "center"
        android: layout_width = "match_parent"
        android: layout_height = "wrap_content">
        <Button
            android: id = "@ + id/button_save"
            android: text = "@ string/save_file"
            android: layout_margin = "20dp"
            android: textSize = "20sp"
            android: layout_width = "wrap_content"
            android: layout_height = "wrap_content" />
        <Button
            android: id = "@ + id/button_read"
            android: text = "@ string/read_file"
            android: textSize = "20sp"
            android: layout_margin = "20dp"
            android: layout_width = "wrap_content"
            android: layout_height = "wrap_content" /></LinearLayout>
    <TextView
        android: id = "@ + id/text_view"
        android: textSize = "30sp"
        android: textColor = "# 000"
        android: layout_margin = "20sp"
        android: layout_width = "wrap_content"
        android: layout_height = "wrap_content" />
</LinearLayout>
Append

try-catch was removed and an error was output.
The error is 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)
When targetPDF is added to FilePath

If FilePath is set not only to the folder name but also to the folder name + file name, the following error is output.

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
  • Answer # 1

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


    Isn't targetPdf used and filePath is up to the folder name?


    I missed it.
    Passing to File is a path, not a URI.
    I don't know how to add targetPdf and tried it, but from what I quoted

      

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

    val filePath = File (applicationContext.filesDir, targetPdf)

    Try

    .

Related articles