Itextpdf库教程中的java.io.FileNotFoundException

时间:2017-05-21 07:04:59

标签: java android itext

我今天一直在尝试使用iTextpdf,但是他遇到了一些粗制错误。 主要是:java.io.FileNotFoundException: /storage/emulated/0/Download/pdfdemo20170521_145348.pdf: open failed: EACCES (Permission denied)

我已经实现了适当的权限,例如

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

但它也不起作用。这是我的文件处理代码:

public class SelfNoteFragment extends Fragment {
private View mRootView;
private EditText mSubjectEditText, mBodyEditText;
private Button mSaveButton;

public SelfNoteFragment() {
    // Required empty public constructor
}

public static SelfNoteFragment newInstance(){
    SelfNoteFragment fragment = new SelfNoteFragment();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mRootView = inflater.inflate(R.layout.fragment_self_note, container, false);
    mSubjectEditText = (EditText) mRootView.findViewById(R.id.edit_text_subject);
    mBodyEditText = (EditText) mRootView.findViewById(R.id.edit_text_body);
    mSaveButton = (Button) mRootView.findViewById(R.id.button_save);

    mSaveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSubjectEditText.getText().toString().isEmpty()){
                mSubjectEditText.setError("Subject is empty");
                mSubjectEditText.requestFocus();
                return;
            }

            if (mBodyEditText.getText().toString().isEmpty()){
                mBodyEditText.setError("Body is empty");
                mBodyEditText.requestFocus();
                return;
            }

            try {
                createPdf();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "FILE", Toast.LENGTH_SHORT).show();
            } catch (DocumentException e) {
                e.printStackTrace();
                Toast.makeText(getActivity(), "Document", Toast.LENGTH_SHORT).show();
            }
        }
    });
    return mRootView;
}


private void createPdf() throws FileNotFoundException, DocumentException {

    File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), "pdfdemo");
    if (!pdfFolder.exists()) {
        pdfFolder.mkdir();
        Log.i("TAG", "Pdf Directory created");
    }

    //Create time stamp
    Date date = new Date() ;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

    //Filename
    File myFile = new File(pdfFolder + timeStamp + ".pdf");

    OutputStream output = new FileOutputStream(myFile);

    //Designate the size
    Rectangle pagesize = new Rectangle(216f, 720f);
    Document document = new Document(pagesize, 36f, 72f, 108f, 180f);

    PdfWriter.getInstance(document, output);

    //OPEN ITEXT FOR DOCUMENT SCANNING
    document.open();

    document.add(new Paragraph(mSubjectEditText.getText().toString()));
    document.add(new Paragraph(mBodyEditText.getText().toString()));

    //If scanning is done, Close the document
    document.close();

}

当我查看我的logcat时,会出现第107行的错误。这是OutputStream output = new FileOutputStream(myFile);

的行

1 个答案:

答案 0 :(得分:2)

对于sdk&gt; = 23,您需要询问Runtime permission

以下是Android Os中所需的list运行时权限。

Oncreate()

使用以下方式询问权限:

if (Build.VERSION.SDK_INT >= 23) {
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED) {
       //you code..
       //read_file()
    } else {
        //request permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    }
}
else { 

    //permission is automatically granted on sdk<23 upon installation
    //Your code
    //read_file()
}

将权限结果捕获到:

    @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {

        case 0: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                //read_file()
            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
 }