Java 无法在android上写入文件

Java 无法在android上写入文件,java,android,Java,Android,我一直在尝试在android上编写PDF文件,当我使用内部存储时,它没有显示错误,但我无法看到创建的文件,如果我更改外部存储路径,即使我在清单文件中授予了权限,我的权限也会被拒绝。 我已经创建了一个类,我正在从活动中调用它来编写文件,它从数据库中获取数据。 这是代码 public boolean createPdfFile(String path, Employee employee,String month,Context context){ boolean status=

我一直在尝试在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;
}

如果您正在为API级别23或更高版本进行开发,则需要明确请求用户的许可

请参阅:

可能的副本