Erreur Java : Je n'arrive pas à retirer mon erreur

Résolu
Bonjour,
J'ai réalisé un programme afin de convertir un fichier csv en xml mais j'ai une erreur "NullPointerException".
A première vue, je connais cette erreur, j'ai une variable vide que j'utilise et cela crée l'erreur (grossièrement).
Cependant, je ne comprends pas pourquoi j'ai cette erreur dans mon programme, je pense pourtant initaliser ma variable .
J'ai tenté différemment de lui donner une valeur mais rien ne fonctionne.
Pensez-vous pouvoir m'aider?
J'ai du sûrement louper quelque chose...
Merci à vous !
PS : j'ai réalisé 2 classes que je vous mets ci-dessous

package image;

import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Window.Type;

import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import com.opencsv.exceptions.CsvException;

//import image.conversion.XMLCreators;

import java.awt.Button;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.awt.event.ActionEvent;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class fenetre extends conversion {
 //char t = ',';
 private JFrame frmFaiaPourFidexpert;
 
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable(){
   public void run(){
    try {
     fenetre window = new fenetre();
     window.frmFaiaPourFidexpert.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 public fenetre(){
  initialize();
 }

 /**
* Initialize the contents of the frame.
*/
 private void initialize(){
  frmFaiaPourFidexpert = new JFrame();
  frmFaiaPourFidexpert.setBackground(new Color(245, 222, 179));
  frmFaiaPourFidexpert.setTitle("FAIA pour FID-Expert");
  frmFaiaPourFidexpert.setForeground(Color.BLACK);
  frmFaiaPourFidexpert.setIconImage(Toolkit.getDefaultToolkit().getImage(fenetre.class.getResource("/image/lux.png")));
  frmFaiaPourFidexpert.setBounds(100, 100, 470, 440);
  frmFaiaPourFidexpert.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frmFaiaPourFidexpert.setResizable(false);
  
  JButton btnNewButton = new JButton("Convertir un fichier");
  btnNewButton.setBounds(0, 302, 456, 29);
  btnNewButton.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    String s = e.getActionCommand();
       
       if (s.equals("Convertir un fichier")) {
        JFileChooser fichier = new JFileChooser( FileSystemView.getFileSystemView().getHomeDirectory());
        fichier.setDialogTitle("Choississez votre fichier .csv");
        fichier.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Fichier .csv","csv");
        fichier.addChoosableFileFilter(filter);
        int res = fichier.showOpenDialog(null);
           // Enregistrez le fichier
           if (res == JFileChooser.APPROVE_OPTION) {
             String XML;
             XML = null;
             
             //File file = fichier.getSelectedFile();
             String fi = fichier.getName();
             XMLCreators xmlCreators = new XMLCreators();
       xmlCreators.convertFile(fi, XML, '\t');
             //conversion.XMLCreators.convertFile(String,String,char);
            
             
             
          }
        ;
         
       }
   }
  });
  frmFaiaPourFidexpert.getContentPane().setLayout(null);
  btnNewButton.setForeground(Color.BLACK);
  btnNewButton.setFont(new Font("Yu Gothic UI", Font.BOLD, 14));
  btnNewButton.setBackground(new Color(168, 146, 28));
  frmFaiaPourFidexpert.getContentPane().add(btnNewButton);
  
  JLabel lblNewLabel = new JLabel("");
  lblNewLabel.setBounds(0, 14, 456, 328);
  lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
  lblNewLabel.setIcon(new ImageIcon(fenetre.class.getResource("/image/fid.png")));
  frmFaiaPourFidexpert.getContentPane().add(lblNewLabel);
  
  JLabel lblNewLabel_1 = new JLabel("                Conversion fichier pour FAIA");
  lblNewLabel_1.setBounds(0, 0, 456, 24);
  lblNewLabel_1.setBackground(new Color(218, 165, 32));
  lblNewLabel_1.setFont(new Font("Microsoft New Tai Lue", Font.BOLD, 18));
  frmFaiaPourFidexpert.getContentPane().add(lblNewLabel_1);
  
  JMenuBar menuBar = new JMenuBar();
  frmFaiaPourFidexpert.setJMenuBar(menuBar);
  
  JMenu mnNewMenu = new JMenu("Aide");
  JMenuItem menuItem = new JMenuItem("?");
  menuItem.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e) {
    String w = e.getActionCommand();
    JFrame frame = new JFrame();
    if (w.equals("?")) {
     JDialog d = new JDialog(frame, "Aide");
     JLabel l = new JLabel("Le bouton convertit un fichier .csv en .xml directement sur votre PC");
     d.getContentPane().add(l);
     d.setIconImage(Toolkit.getDefaultToolkit().getImage(fenetre.class.getResource("/image/lux.png")));
     d.setSize(400,100);
     d.setVisible(true);
    }
   }
  });
  mnNewMenu.add(menuItem);
  menuBar.add(mnNewMenu);
 }

}

package image;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class conversion {
    public static void main(String[] args) {
        new conversion();
    }

   // public conversion(){
    //    new XMLCreators().convertFile("Test.csv", "Test.xml", '\t');
    //}

    public class XMLCreators {
        // Protected Properties

        protected DocumentBuilderFactory domFactory = null;
        protected DocumentBuilder domBuilder = null;

        public XMLCreators(){
            try {
                domFactory = DocumentBuilderFactory.newInstance();
                domBuilder = domFactory.newDocumentBuilder();
            } catch (FactoryConfigurationError exp) {
                System.err.println(exp.toString());
            } catch (ParserConfigurationException exp) {
                System.err.println(exp.toString());
            } catch (Exception exp) {
                System.err.println(exp.toString());
            }
        }

        public int convertFile(String csvFileName, String xmlFileName, char delimiter) {

            int rowsCount = -1;
            BufferedReader csvReader;
            try {
                Document newDoc = domBuilder.newDocument();
                // Root element
                Element rootElement = newDoc.createElement("XMLCreators");
                newDoc.appendChild(rootElement);
                // Read csv file
                csvReader = new BufferedReader(new FileReader(csvFileName));

                //** Now using the OpenCSV **//
                CSVParser parser = new CSVParserBuilder()
                        .withSeparator(delimiter)
                        .build();

                CSVReader reader = new CSVReaderBuilder(new FileReader(csvFileName))
                        .withCSVParser(parser)
                        .build();
                //CSVReader reader = new CSVReader(csvReader);
                String[] nextLine;
                int line = 0;
                List<String> headers = new ArrayList<String>(5);
                while ((nextLine = reader.readNext()) != null) {
                    if (line == 0) { // Header row
                        for (String col : nextLine) {
                            headers.add(col);
                        }
                    } else { // Data row
                        Element rowElement = newDoc.createElement("row");
                        rootElement.appendChild(rowElement);

                        int col = 0;
                        for (String value : nextLine) {
                            String header = headers.get(col).replaceAll("[\\t\\p{Zs}\\u0020]", "_");

                            Element curElement = newDoc.createElement(header);
                            curElement.appendChild(newDoc.createTextNode(value.trim()));
                            rowElement.appendChild(curElement);

                            col++;
                        }
                    }
                    line++;
                }
                //** End of CSV parsing**//

                FileWriter writer = null;

                try {

                    writer = new FileWriter(new File(xmlFileName));

                    TransformerFactory tranFactory = TransformerFactory.newInstance();
                    Transformer aTransformer = tranFactory.newTransformer();
                    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                    aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                    Source src = new DOMSource(newDoc);
                    Result result = new StreamResult(writer);
                    aTransformer.transform(src, result);

                    writer.flush();

                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                }

                // Output to console for testing
                // Resultt result = new StreamResult(System.out);
            } catch (IOException exp) {
                exp.printStackTrace();
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            return rowsCount;
            // "XLM Document has been created" + rowsCount;
        }
    }
}

2 réponses

  1. Modérateur
    Bonjour,

    Pourrais tu poster également la stack trace de l'exception, elle indique exactement sur quelle ligne est l'erreur, donc ça aide à savoir quel code pose problème.
    0
    1. Bonjour! Oui bien sûr la voici :
      java.lang.NullPointerException
       at java.base/java.io.FileInputStream.<init>(FileInputStream.java:145)
       at java.base/java.io.FileInputStream.<init>(FileInputStream.java:108)
       at java.base/java.io.FileReader.<init>(FileReader.java:60)
       at image.conversion$XMLCreators.convertFile(conversion.java:70)
       at image.fenetre$2.actionPerformed(fenetre.java:83)
       at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
       at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
       at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
       at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
       at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
       at java.desktop/java.awt.Component.processMouseEvent(Component.java:6617)
       at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
       at java.desktop/java.awt.Component.processEvent(Component.java:6382)
       at java.desktop/java.awt.Container.processEvent(Container.java:2264)
       at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
       at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
       at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
       at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
       at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4563)
       at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
       at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
       at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
       at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
       at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
       at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
       at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
       at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
       at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
       at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
       at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
       at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
       at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
       at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
       at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
       at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
       at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
       at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
       at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
       at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
       at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
      0
    2. @caramelwillyJ'ai résolu mon erreur... !
      J'avais mal compris l'utilisation du getName() de JFileChooser.
      Désormais mon csvReader n'est plus null!
      Mais j'ai une autre erreur que je ne comprends pas, comment peut il être introuvable? :
      java.io.FileNotFoundException: GL 2017.csv (Le fichier spécifié est introuvable)
      GL 2017.csv
       at java.base/java.io.FileInputStream.open0(Native Method)
       at java.base/java.io.FileInputStream.open(FileInputStream.java:211)
       at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153)
       at java.base/java.io.FileInputStream.<init>(FileInputStream.java:108)
       at java.base/java.io.FileReader.<init>(FileReader.java:60)
       at image.conversion$XMLCreators.convertFile(conversion.java:70)
       at image.fenetre$2.actionPerformed(fenetre.java:84)
       at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
       at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
       at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
       at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
       at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
       at java.desktop/java.awt.Component.processMouseEvent(Component.java:6617)
       at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
       at java.desktop/java.awt.Component.processEvent(Component.java:6382)
       at java.desktop/java.awt.Container.processEvent(Container.java:2264)
       at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
       at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
       at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
       at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
       at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4563)
       at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
       at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
       at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
       at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
       at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
       at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
       at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
       at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
       at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
       at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
       at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
       at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
       at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
       at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
       at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
       at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
       at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
       at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
       at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
       at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
       at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

      Merci de votre aide !
      0
    3. Modérateur
      @caramelwillygetName() ne renvoie que le nom du fichier (GL 2017.csv dans l'erreur), donc par défaut Java va le chercher dans son répertoire de travail, où de toute évidence le fichier n'est pas.

      Il faudrait plutôt utiliser getSelectedFile() pour récupérer le chemin d'accès complet du fichier (C:/.../GL 2017.csv)
      1
    4. @KXJe te remercie !
      En effet j'avais mal utilisé la fonction getName(), enfin mal compris son utilisation.
      Maintenant, j'ai un soucis que je ne comprends pas : "INVALID_CHARACTER_ERR : an invalid or illegal XML character is specified".
      C'est ligne 97 "Element curElement = newDoc.createElement(header);" pourtant cela me parait correct et a bien l'air de respecter les conditions d'un fichier XML. J'ai supprimé tous les moindres espaces que je pouvais trouver, j'ai changé les noms de quelques de mes variables pour ne plus avoir "XML" dedans, au cas où. Mais rien n'y fait.
      Je ne comprends pas où se situe l'erreur.
      Merci de ton aide!
      0
    5. Modérateur
      @caramelwillyIci on ne sait pas trop ce que tu manipules comme données, le mieux serait d'intercepter l'exception pour l'enrichir de la donnée manipulée lors de l'erreur.

      Exemple :
      String header = headers.get(col).replaceAll("[\\t\\p{Zs}\\u0020]", "_");
      Element curElement;
      try {
          curElement = newDoc.createElement(header);
      } catch (Exception e) {
          throw new RuntimeException("Can't createElement [" + header + "] for col=" + col, e);
      }

      À mon avis ton replaceAll est à revoir, j'ai du mal à comprendre ce que tu essaies de faire avec ta regex, elle est probablement incorrecte d'où ton erreur.
      1
  2. Bonjour.

    Je me permets de revenir vers vous car j'aimerais complexifier un peu mon programme.

    Est-il possible de faire différentes "sections" sur mon fichier XML et de rediriger mes fichiers csv vers chaque section.

    Du type je dois sélectionner 3 fichiers en entrée :

    -fichier1

    -fichier2

    -fichier3

    Et mon XML doit se former comme suit :

    <General>
    
           <section 1>
    
            fichier1 converti
    
            </Section1>
    
            <section2>
    
            fichier2 converti
    
            </section2>
    
            <section3>
    
            fichier3 converti
    
            </section3>
    
    </general>

    Je sais déjà que pour pouvoir choisir plusieurs fichiers j'utilise la fonction "fichier.setMultiSelectionEnabled(true);"

    Maintenant je cherche à rediriger les fichiers dans mon programme conversion, et de créer un XML avec 3 sections.

    Je pensais faire un "if nom_du_fichier == fichier1 ==> fichier 1 est converti dans la section1"

    Mais je suis un peu perdu quant à rediriger le fichier vers une section que j'aurais créé.

    De plus, j'ai modifié du coup la class conversion comme suit :

    package image;
    import java.io.*;
    import java.util.Scanner;
    
    public class conversion {
    	static int i=0;
        public static void convert(File csvFile, File xmlFile) {
            try (Scanner sc = new Scanner(csvFile); PrintWriter pw = new PrintWriter(xmlFile)) {
                String[] headers = sc.nextLine().split(";");
                pw.println("<AuditFile>");
                while (sc.hasNextLine()) {
                    String[] values = sc.nextLine().split(";");
                    pw.println("  <Header>");
                    for (int i = 0; i < values.length && i < headers.length; i++) {
                        pw.println("    <" + headers[i] + ">" + values[i] + "</" + headers[i] + ">");
                    }
                    pw.println("  </Header>");
                    
                }
                while (sc.hasNextLine()) {
                    String[] values = sc.nextLine().split(";");
                    pw.println("  <section2>");
                    for (int i = 0; i < values.length && i < headers.length; i++) {
                        pw.println("    <" + headers[i] + ">" + values[i] + "</" + headers[i] + ">");
                    }
                    pw.println("  </section2>");
                    
                }
                while (sc.hasNextLine()) {
                    String[] values = sc.nextLine().split(";");
                    pw.println("  <section3>");
                    for (int i = 0; i < values.length && i < headers.length; i++) {
                        pw.println("    <" + headers[i] + ">" + values[i] + "</" + headers[i] + ">");
                    }
                    pw.println("  </section3>");
                    
                }
                pw.println("</AuditFile>");
                
            } catch (IOException e) {
                throw new UncheckedIOException("Can't convert " + csvFile + " to " + xmlFile, e);
            }
        }
    }

    Merci de votre aide!

    0