【问题标题】:Android create file causing java.io.IOExceptionAndroid 创建文件导致 java.io.IOException
【发布时间】:2018-11-10 12:05:07
【问题描述】:

我正在尝试实现一种在我的应用程序中创建 pdf 文件的方法。目前我正在为此使用 PDF Writer APW。我遵循instruction from jguerinet 并将所有必要的文件粘贴到项目中(作为新包)。但是当我运行代码时,我总是得到以下异常。我还尝试使用 File downloads = Environment.getExternalStorageDirectory(); 而不是 File downloads = Environment.getDataDirectory(); 没有任何成功。谁能告诉我,我做错了什么?

2018-11-10 12:52:38.843 31238-31238/com.abc.systeminfo I/PDF: Writing file to /data/PDFWriterAPW.pdf
2018-11-10 12:52:38.845 31238-31238/com.abc.systeminfo W/PDF IOException: java.io.IOException: Permission denied
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
        at java.io.File.createNewFile(File.java:1000)
        at com.abc.systeminfo.CreateFile.outputToFile(CreateFile.java:72)
        at com.abc.systeminfo.CreateFile.<init>(CreateFile.java:28)
        at com.abc.systeminfo.ActivityStart$1.onClick(ActivityStart.java:54)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

CreateFile.java

package com.abc.systeminfo;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import crl.android.pdfwriter.PDFWriter;
import crl.android.pdfwriter.StandardFonts;
import crl.android.pdfwriter.Transformation;

public class CreateFile {

    PDFWriter mPDFWriter;
    String pdfcontent;
    String encoding = "ISO-8859-1";
    String fileName = "PDFWriterAPW.pdf";

    public CreateFile(String pdfcontent) {
        mPDFWriter = new PDFWriter();
        this.pdfcontent = pdfcontent;   // will be used later instead of String s
        String s = generateHelloWorldPDF();

        outputToFile(fileName, s, encoding);
    }

    public String generateHelloWorldPDF() {
        mPDFWriter.setFont(StandardFonts.SUBTYPE, StandardFonts.TIMES_ROMAN);
        mPDFWriter.addRawContent("1 0 0 rg\n");
        mPDFWriter.addTextAsHex(70, 50, 12, "68656c6c6f20776f726c6420286173206865782921");
        mPDFWriter.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER, StandardFonts.WIN_ANSI_ENCODING);
        mPDFWriter.addRawContent("0 0 0 rg\n");
        mPDFWriter.addText(30, 90, 10, "� CRL", Transformation.DEGREES_270_ROTATION);

        mPDFWriter.newPage();
        mPDFWriter.addRawContent("[] 0 d\n");
        mPDFWriter.addRawContent("1 w\n");
        mPDFWriter.addRawContent("0 0 1 RG\n");
        mPDFWriter.addRawContent("0 1 0 rg\n");
        mPDFWriter.addRectangle(40, 50, 280, 50);
        mPDFWriter.addText(85, 75, 18, "Code Research Laboratories");

        mPDFWriter.newPage();
        mPDFWriter.setFont(StandardFonts.SUBTYPE, StandardFonts.COURIER_BOLD);
        mPDFWriter.addText(150, 150, 14, "http://coderesearchlabs.com");
        mPDFWriter.addLine(150, 140, 270, 140);

        int pageCount = mPDFWriter.getPageCount();
        for (int i = 0; i < pageCount; i++) {
            mPDFWriter.setCurrentPage(i);
            mPDFWriter.addText(10, 10, 8, Integer.toString(i + 1) + " / " + Integer.toString(pageCount));
        }

        String s = mPDFWriter.asString();
        return s;
    }

    private void outputToFile(String fileName, String pdfContent, String encoding) {
        File downloads = Environment.getDataDirectory();
        //File downloads = Environment.getExternalStorageDirectory();
        if (!downloads.exists() && !downloads.mkdirs())
            throw new RuntimeException("Could not create download folder");

        File newFile = new File(downloads, fileName);
        Log.i("PDF", "Writing file to " + newFile);

        try {
            newFile.createNewFile();
            try {
                FileOutputStream pdfFile = new FileOutputStream(newFile);
                pdfFile.write(pdfContent.getBytes(encoding));
                pdfFile.close();
            } catch (FileNotFoundException e) {
                Log.w("PDF FileNotFound ", e);
            }
        } catch (IOException e) {
            Log.w("PDF IOException", e);
        }
    }

}

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abc.systeminfo">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ActivityStart">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

【问题讨论】:

    标签: android file exception ioexception


    【解决方案1】:

    在执行如下操作之前,您需要在运行时请求权限(这对于使用棒棒糖及以上安卓操作系统的设备是必需的)

    if (ContextCompat.checkSelfPermission(thisActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
        // Permission is not granted
         if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
        } else {
            // No explanation needed; request the permission
            ActivityCompat.requestPermissions(thisActivity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
        }
    }
    

    【讨论】:

    • 这适用于在外部存储上写入。非常感谢你。但是为什么我不能使用File downloads = Environment.getDataDirectory(); 将文件写入内部存储?
    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2020-08-11
    • 2012-08-05
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多