Vous utilisez un navigateur obsolète, veuillez le mettre à jour.
Veuillez utiliser un navigateur internet moderne avec JavaScript activé pour naviguer sur OpenClassrooms.com
Une question ? Pas de panique, on va vous aider !
Bonjour tout le monde j'aimerais que vous m'aidiez à enregistrer et à lire des objets dans un fichier
Voici le bout de code que j'ai pour sérialiser
ArrayList<Products> prod = new ArrayList<>(); ArrayList<Products> prode = new ArrayList<>(); Products product; JButton btnNewButton = new JButton("Ajouter"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String id = textField.getText(); String name = textField_1.getText(); String cat = comboBox.getActionCommand(); int quant = textField_4.getX(); int price = textField_2.getY(); product = new Products(id, name, cat, quant, price); prod.add(product); ObjectOutputStream oos = null; FileOutputStream fos = null; try { oos = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream( new File("ProdFile.txt")))); oos.writeObject(product); oos.close(); Table(); JOptionPane.showMessageDialog(null, "Produit enrégistré avec Succès"); }catch (IOException eio){ eio.printStackTrace(); } finally { if (fos != null) { safeClose(fos); } } Table(); }
j'ai créer une fonction pour désérialiser dans un Jtable
public void Table() { String [] produit = {"ID", "Nom du Produit", "Catégorie", "Quantité", "Prix"}; String [] afficher = new String [6]; DefaultTableModel model = new DefaultTableModel(null, produit); ObjectInputStream ois = null; FileInputStream fis = null; try { fis = new FileInputStream(new File("ProdFile.txt")); ois = new ObjectInputStream(fis); prode = (ArrayList<Products>) ois.readObject(); for(Products i : prode) { afficher[0] = i.getId(); afficher[1] = i.getName(); afficher[2] = i.getCategory(); afficher[3] = i.getCategory(); afficher[4] = i.getCategory(); model.addRow(afficher); } table.setModel(new DefaultTableModel( new Object[][] { {null, null, null, null, null}, }, new String[] { "ID", "Nom du Produit", "Cat\u00E9gorie", "Quantit\u00E9", "Prix" } )); } catch (Exception ex) { ex.printStackTrace(); } }
PXL Le retro gaming facile Thread sur le forum: https://openclassrooms.com/forum/sujet/retro-pxl
Bonjour,
Tu écris tes objets un par un dans ton fichier. Il faut donc les récupérer un par un.
brubru777 a écrit:
Bonjour, Tu écris tes objets un par un dans ton fichier. Il faut donc les récupérer un par un.
Comment les écrire à plusieurs alors ?
Vous pouvez rédiger votre message en Markdown ou en HTML uniquement.
PXL Le retro gaming facile Thread sur le forum: https://openclassrooms.com/forum/sujet/retro-pxl