Exception java.lang.NullPointerException with an open file

0

I run a main that generates a PDF file. I have that PDF open, if I try to run that main again, it gives me the following error:

Exception in thread "main" java.lang.NullPointerException
    at bbdd.PDF_Clientes_Tabla.crearPDF(PDF_Clientes_Tabla.java:161)
    at bbdd.Main_PDF_Clientes_Tabla.main(Main_PDF_Clientes_Tabla.java:22)
Java Result: 1

How can you control that exception? With try-catch? Or would it be necessary to examine if the file exists with the .exists() method?

Code:

public class Main_PDF_Clientes_Tabla {
    /**
     * Main.
     * @param args
     * @throws DocumentException 
     */
    public static void main(String[] args) throws DocumentException{
        //Almacenamos en un arrayList de clientes llamado "ArrayList<Cliente> clientes"
        //todos los datos de la función "ConexionesPDFTabla.listado_clientes();".
        try{
            ArrayList<Cliente> clientes = ConexionesPDFTabla.listado_clientes();
            PDF_Clientes_Tabla.crearPDF(clientes);
            System.out.println("PDF creado correctamente en el directorio actual.");
        }catch(DocumentException ex){
            ex.getMessage();
        }
    }
}


public static void crearPDF(ArrayList<Cliente> clientes) throws DocumentException{
        //Declaramos un documento como un objecto Document. 
        Document documento = new Document(PageSize.LETTER, 80, 80, 75, 75);
        //writer es declarado como el método utilizado para escribir en el archivo.
        PdfWriter writer = null;

        try{
            //Obtenemos la instancia del archivo a utilizar.
            writer = PdfWriter.getInstance(documento, new FileOutputStream(archivo));
        }catch(FileNotFoundException | DocumentException ex){
            ex.getMessage();
        }

        //Agregamos un título al documento.
        documento.addTitle("ARCHIVO PDF GENERADO DESDE JAVA");

        //Abrimos el documento a editar.
        documento.open();

        try{
            //Obtenemos la instancia de la imagen/logo.
            Image imagen = Image.getInstance("..\imagenes\LOGO.png");
            //Alineamos la imagen al centro del documento.
            imagen.setAlignment(Image.ALIGN_CENTER);
            //Agregamos la imagen al documento.
            documento.add(imagen);
        }catch(IOException | DocumentException ex){
            ex.getMessage();
        }

        //Creamos un párrafo nuevo llamado "vacio1" para espaciar los elementos.
        Paragraph vacio1 = new Paragraph();
        vacio1.add("\n\n");
        documento.add(vacio1);

        //Declaramos un texto llamado "titulo" como Paragraph. 
        //Le podemos dar formato alineado, tamaño, color, etc.
        Paragraph titulo = new Paragraph();
        titulo.setAlignment(Paragraph.ALIGN_CENTER);
        titulo.setFont(FontFactory.getFont("Times New Roman", 24, Font.BOLD, BaseColor.RED));
        titulo.add("***LISTADO DE CLIENTES***");

        try{
            //Agregamos el texto "titulo" al documento.
            documento.add(titulo);
        }catch(DocumentException ex){
            ex.getMessage();
        }

        //Creamos un párrafo nuevo llamado "saltolinea1" simulando un salto de linea para espaciar
        //los elementos del PDF.
        Paragraph saltolinea1 = new Paragraph();
        saltolinea1.add("\n\n");
        documento.add(saltolinea1);

        //Añadimos una tabla de 7 columnas. 
        PdfPTable tabla = new PdfPTable(7); 
        //Datos de porcentaje a la tabla (tamaño ancho).
        tabla.setWidthPercentage(120);
        //Datos del ancho de cada columna.
        tabla.setWidths(new float[] {12, 18, 10, 12, 20, 14, 24});

        //Añadimos los títulos a la tabla. 
        Paragraph columna1 = new Paragraph("NOMBRE");
        columna1.getFont().setStyle(Font.BOLD);
        columna1.getFont().setSize(9);
        tabla.addCell(columna1);

        Paragraph columna2 = new Paragraph("APELLIDOS");
        columna2.getFont().setStyle(Font.BOLD);
        columna2.getFont().setSize(9);
        tabla.addCell(columna2);

        Paragraph columna3 = new Paragraph("DNI");
        columna3.getFont().setStyle(Font.BOLD);
        columna3.getFont().setSize(9);
        tabla.addCell(columna3);

        Paragraph columna4 = new Paragraph("TELÉFONO");
        columna4.getFont().setStyle(Font.BOLD);
        columna4.getFont().setSize(9);
        tabla.addCell(columna4);

        Paragraph columna5 = new Paragraph("DIRECCION");
        columna5.getFont().setStyle(Font.BOLD);
        columna5.getFont().setSize(9);
        tabla.addCell(columna5);

        Paragraph columna6 = new Paragraph("CIUDAD");
        columna6.getFont().setStyle(Font.BOLD);
        columna6.getFont().setSize(9);
        tabla.addCell(columna6);

        Paragraph columna7 = new Paragraph("EMAIL");
        columna7.getFont().setStyle(Font.BOLD);
        columna7.getFont().setSize(9);
        tabla.addCell(columna7);

        //Recorremos cada arrayList e imprimimos los resultados. 
        for (int i = 0; i<clientes.size(); i++){ 
            columna1 = new Paragraph(clientes.get(i).getNombre());
            columna1.getFont().setSize(7);
            tabla.addCell(columna1);

            columna2 = new Paragraph(clientes.get(i).getApellidos());
            columna2.getFont().setSize(7);
            tabla.addCell(columna2);

            columna3 = new Paragraph(clientes.get(i).getDNI());
            columna3.getFont().setSize(7);
            tabla.addCell(columna3);

            columna4 = new Paragraph(clientes.get(i).getTlf_contacto());
            columna4.getFont().setSize(7);
            tabla.addCell(columna4);

            columna5 = new Paragraph(clientes.get(i).getDireccion());
            columna5.getFont().setSize(7);
            tabla.addCell(columna5);

            columna6 = new Paragraph(clientes.get(i).getCiudad());
            columna6.getFont().setSize(7);
            tabla.addCell(columna6);

            columna7 = new Paragraph(clientes.get(i).getEmail());
            columna7.getFont().setSize(7);
            tabla.addCell(columna7);
        } 

        //Añadimos la tabla "tabla" al documento "documento".
        documento.add(tabla);   
        //Cerramos el documento.
        documento.close();
        //Cerramos el writer.
        writer.close();
    }
    
asked by omaza1990 30.12.2016 в 14:16
source

2 answers

2

You have 2 options:

  • Control the exception with an additional generic catch so that it does not fail:
  • try {
        //Obtenemos la instancia del archivo a utilizar.
        writer = PdfWriter.getInstance(documento, new FileOutputStream(archivo));
    } catch(FileNotFoundException | DocumentException ex) {
        ex.getMessage();
    } catch(Exception ex) {
        ex.getMessage();
    }
    
  • Check if the file exists and change the name if it is the case:
  • try {
        //Si el fichero existe generamos otro nombre
        String nombre = archivo;
        int counter = 1;
        while(new File(nombre).exists()) {
            //Está linea de código obviamente no funcionaría ya que habría que tener en cuenta la extensión
            nombre = archivo + counter.toString();
            counter++;
        }
        //Obtenemos la instancia del archivo a utilizar.
        writer = PdfWriter.getInstance(documento, new FileOutputStream(nombre));
    } catch(FileNotFoundException | DocumentException ex) {
        ex.getMessage();
    }
    

    You can also combine the 2 options

        
    answered by 30.12.2016 / 14:49
    source
    1

    If you have opened the pdf with another program you will not be able to close the writer or save the changes, the same thing will happen if you open it with 2 programs at the same time and try to save it.

    You can show a message in case it is opened by another program or perform X action, checking it like this:

    //archivo=nombre del pdf
    //Intentaremos guardar una copia del mismo fichero que tenemos para comprobar si nos deja guardarlo, si no nos deja es que esta abierto por otro programa
     File file = new File(archivo);
    
        File sameFileName = new File(archivo);
        if(file.renameTo(sameFileName)){
            // 
            System.out.println("El fichero no esta pillado por ningún programa, podemos guardar los cambios");  
            writer.close(); 
        }else{
            // El fichero esta abierto, mostrar mensaje para avisar al usuario de ello o realizar X acción
            System.out.println("El fichero esta abierto por otro programa");
    
        }
    
        
    answered by 30.12.2016 в 14:53