Android创建文件导致java.io.IOException

时间:2018-11-10 12:05:07

标签: android file exception ioexception

我正在尝试实现一种在我的应用中创建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>

1 个答案:

答案 0 :(得分:0)

您需要先在运行时请求权限,然后再执行以下操作(对于使用棒棒糖的设备以及android os以上的设备,这是必需的)

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);
    }
}