无法在android上写文件

时间:2017-04-04 03:08:15

标签: java android

我一直在尝试在Android上编写PDF文件,当我使用内部存储时它显示没有错误但我无法看到创建的文件,如果我改变了外部存储的路径,即使我已经给出了我的权限被拒绝我的清单文件中的权限。 我创建了一个类,我从活动中调用它来编写从数据库中获取数据的文件。 这是代码。

      public boolean createPdfFile(String path, Employee employee,String month,Context context){
    boolean status=false;
    if(path!=null && employee!=null){
        Document document=new Document();
        try{
            if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
                Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
            }
            File sdCard=Environment.getExternalStorageDirectory();
            File file=new File(sdCard,month+"_"+employee.getEmployeeName()+".pdf");
            PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(file));
            writer.setEncryption(employee.getDateOfBirth().getBytes(),employee.getEmployeeName().getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
            document.open();
            Paragraph p=new Paragraph();
            p.add("Payslip for the month of January");
            p.setFont(new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(1, 1, 1)));
            p.setAlignment(Element.ALIGN_CENTER);
            document.add(p);
            PdfPTable table=new PdfPTable(2);
            table.setWidthPercentage(100); //Width 100%
            table.setSpacingBefore(10f); //Space before table
            table.setSpacingAfter(10f); //Space after table
            float[] columnWidths = {1.5f, 1.5f};
            table.setWidths(columnWidths);
            table.addCell("Employee Code");
            table.addCell(employee.getEmployeeID());
            table.addCell("Department");
            table.addCell(employee.getDepartment().getDepartmentName());
            table.addCell("Date of Birth");
            table.addCell(employee.getDateOfBirth());
            table.addCell("Date of Joining");
            table.addCell(employee.getDateOfJoining());
            table.addCell("Employee Name");
            table.addCell(employee.getEmployeeName());
            document.add(table);
            document.close();
            writer.close();
            status=true;
        }catch (FileNotFoundException e) {
            status=false;
            Log.e("PDF exception aaa",e.getMessage());
        }catch (DocumentException e) {
            status=false;
            Log.e("PDF exception abc",e.getMessage());
        } catch (IOException e) {
            status=false;
            Log.e("PDF exception",e.getMessage());
        }
    }
    return status;
}

1 个答案:

答案 0 :(得分:0)

如果您正在为API级别23或更高级别开发,则需要明确要求用户许可。

请参阅:https://developer.android.com/training/permissions/requesting.html#perm-check