2013-01-04 3 views
1

Je sauvegarde un fichier .txt et .doc contenant les données de ma JTable. À la minute où il l'enregistre, il place le texte comme dans une table, mais en raison de la longueur différente des données, il ne rentre pas. Donc, je suis en train d'obtenir la date de poser comme suit:Enregistrement de JTable en tant que fichier texte

Colonne 1 Nom: ligne 1 colonne 1 Données

Colonne 2 Nom: ligne 1 colonne 2 données

Colonne 3 Nom: ligne 1 colonne 3 données

colonne 4 nom: ligne 1 colonne 4 données

colonne 1 nom: ligne 2 colonne 1 données

colonne 2 nom: ligne 2 colonne 2 données

Colonne 3 Nom: ligne 2 colonne 3 Données

Colonne 4 Nom: ligne 2 colonne 4 Données

etc.

Le code que j'ai à la minute est:

private void saveResultsActionPerformed(ActionEvent evt) { 


    int returnVal = fileChooser.showSaveDialog(NewJFrame.this); 
    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     try { 
      File file = fileChooser.getSelectedFile(); 
      PrintWriter os = new PrintWriter(file); 
      os.println(""); 
      for (int col = 0; col < table.getColumnCount(); col++) { 
       os.print(table.getColumnName(col) + "\t"); 
      } 

      os.println(""); 
      os.println(""); 

      for (int i = 0; i < table.getRowCount(); i++) { 
       for (int j = 0; j < table.getColumnCount(); j++) { 
        os.print(table.getValueAt(i, j).toString() + "\t"); 

       } 
       os.println(""); 
      } 
      os.close(); 
      System.out.println("Done!"); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

Mais gardez à l'esprit que chacune de mes tables a un nombre différent de colonnes et de lignes. J'ai essayé d'enregistrer les colonnes et les données dans les tableaux, et j'ai le sentiment que c'est la bonne façon de contourner le problème, mais je ne sais pas comment l'imprimer dans l'ordre que j'ai mentionné,

Répondre

2

L'algorithme est assez simple :

for (int row = 0; row < table.getRowCount(); row++) { 
    for (int col = 0; col < table.getColumnCount(); col++) { 
     os.print(table.getColumnName(col)); 
     os.print(": "); 
     os.println(table.getValueAt(row, col)); 
    } 
} 
+0

Salut, Merci pour votre réponse! Cet algorithme ne fonctionne pas car il imprime 'colonne 1 Nom: ligne 1 colonne 1 colonne de données 1 nom: ligne 1 colonne 2 colonne de données 1 nom: ligne 1 colonne 3 données' et ainsi de suite –

+0

Aucun moyen: à chaque itération, col est incrémenté, et le nom de la colonne pour cette col est affiché. –

+0

Désolé mal lu votre message. Fonctionne parfaitement, merci beaucoup! –

0

Un exemple minimal que j'ai fait est fourni ci-dessous. Je donne la forme de sortie suivante:

Prénom: Kathy
Nom: Smith
Sport: Snowboard
Nombre d'années: 5

Prénom: John
Nom: Doe
Sport: aviron
Nombre d'années: 2

 String[] columnNames = {"First Name", "Last Name","Sport","# of Years"}; 

    Object[][] data = { 
      {"Kathy", "Smith", "Snowboarding", "5"}, 
      {"John", "Doe", "Rowing", "2"}, 
      {"Sue", "Black", "Knitting", "8"}, 
      {"Jane", "White", "Speed reading", "10"}, 
      {"Joe", "Brown", "Pool", "20"} 
    }; 

    JTable table = new JTable(data, columnNames); 

    for(int row = 0; row < table.getRowCount(); row++) { 

     for(int column = 0; column < table.getColumnCount(); column++) { 
      System.out.print(table.getColumnName(column) + ": "); 
      System.out.println(table.getValueAt(row, column)); 
     } 
     System.out.println(""); // Add line space 
    } 
0

Le code suivant utilise des sous-chaînes pour permettre aux colonnes d'être ordonnées dans le fichier texte. C'est un peu brouillon mais la première pour la boucle gère les en-têtes de colonne et la seconde pour la boucle gère toutes les données. Si vous voulez changer la taille de chaque morceau de données, changez 20 à votre taille préférée.

BufferedWriter bfw = new BufferedWriter(new FileWriter(
        "Data.txt")); 

      for (int i = 0; i < table.getColumnCount(); i++) {//first loop is used for titles of each column 

       String name = String.valueOf(table.getColumnName(i)); 

       if (name.length() > 20) {//20 (characters long) is the constant I chose to make each value 
        name = name.substring(0, 20); 
       } else if (name.length() == 20) { 

       } else { 
        String spaces = ""; 
        int diff = 20 - name.length(); 
        while (diff > 0) { 
         spaces = spaces + " "; 
         diff--; 
        } 
        name = name.concat(spaces); 
       } 

       bfw.write(name); 
       bfw.write("\t"); 
      } 

      for (int i = 0; i < table.getRowCount(); i++) {//for all the data in the Jtable excluding column headers 
       bfw.newLine(); 
       for (int j = 0; j < table.getColumnCount(); j++) { 

        if (table.getValueAt(i, j) == null) { 
         bfw.write("     "); 
         bfw.write("\t"); 
        } 

        else { 

         String name = String.valueOf((table 
           .getValueAt(i, j))); 

         if (name.contains("(")) { 
          name = name.substring(0, name.indexOf("(")); 
         } 

         if (name.length() > 20) { 
          name = name.substring(0, 20); 
         } else if (name.length() == 20) { 

         } else { 
          String spaces = ""; 
          int diff = 20 - name.length(); 
          while (diff > 0) { 
           spaces = spaces + " "; 
           diff--; 
          } 
          name = name.concat(spaces); 
         } 

         bfw.write(name); 
         bfw.write("\t"); 
        } 
       } 
      } 
0

En plus des réponses déjà fournies, j'ai mis en place une solution qui sauvegarde le contenu dans un fichier texte de type .csv (valeurs séparées par des virgules).

  • Premièrement, j'ai créé une méthode qui place le contenu d'un JTable dans un tableau bidimensionnel de type Object. J'ai choisi le type Objet parce que diverses colonnes dans une JTable peuvent stocker différents types de données, par exemple. nombres, cordes etc.Cette méthode se trouve dans mon front-end GUI:

     /** 
         * 
         * This method extrapolates the data from the JTable and places 
         * it into a two-dimensional object array. <p> 
         * 
         * It then returns the object array in preparation for writing 
          to disk 
         * 
         * 
         * @param aTable - the selected table for rendering into a two- 
    
          dimensional object array 
         * 
         * @return Object[][] - the two-dimensional object array which 
    
          shall be written to disk 
         * 
         * @see 
         * 
         */ 
         public Object[][] getTableData(JTable aTable) 
         { 
    
          int rowCount = aTable.getModel().getRowCount(); 
          int columnCount = aTable.getModel().getColumnCount(); 
    
          Object[][] curTableData = 
    
           new Object[rowCount][columnCount]; 
    
          for (int row = 0; row < rowCount; row++) 
          { 
          for (int column = 0; column < columnCount; column++) 
          { 
    
           curTableData[row][column] = 
            aTable.getModel().getValueAt(row,column); 
    
        //   System.out.println("curTableData["+row+"]["+column+"] = "+curTableData[row][column]); 
    
          } 
          } 
    
          return curTableData; 
    
         } 
    
  • Deuxièmement, j'ai créé une classe qui est responsable de la rédaction du contenu du tableau d'objets en deux dimensions (contenu JTable) sur le disque. Ceci est décrit ci-dessous:

    import java.io.*; 
    
    /** 
    * 
    * This class is responsible for writing the 2D object to disk. 
    * The 2d Object contains your JTable contents 
    * <p> 
    * 
    * @author  Mark Burleigh 
    * @version  %I%, %G% 
    * @since  1.0 
    * 
    */ 
    public class WriteJTableContents 
    { 
    /** 
    * 
    * This constructor takes in two parameters. It is also responsible 
    * for writing the JTable contents to disk (to csv file) 
    * 
    * 
    * @param aData - the JTable data to be saved to disk 
    * @param afile - the name of the file where the data shall be saved 
    * (this is a .CSV type file) 
    * 
    * 
    */ 
        public WriteRandomSampleData(Object[][] aData, String afile) 
        { 
         writeToDisk(aData,afile); 
    
        // This method prints the two-dimensional array to the command console 
        // printData(); 
    
        } 
    
        /** 
        * 
        * This method is responsible for writing the contents of a JTable (2d 
        * array object) to disk (csv text file) 
        * <p> 
        * 
        * @param aData - the 2D data (Jtable contents) to be stored to disk 
        * @param aDatafile - the file where the data shall be stored 
        * to disk. This shall be of type.CSV 
        * 
        * @return 
        * 
        * @see 
        * 
        */ 
        public void writeToDisk(Object[][] aData, String aDatafile) 
        { 
    
        try 
        { 
    
         FileOutputStream fout = new FileOutputStream(aDatafile, false); 
    
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fout)); 
    
         //Headers 
         bw.append("Script No., Candidate No., Mark, Grade,Script No., Candidate No., Mark, Grade"); 
         // End of data row (Jable row) so append new line character in csv file 
         bw.append('\n'); 
    
         for (int row = 0; row < aData.length; row++) 
         { 
    
          for (int column = 0; column < aData[row].length; column++) 
          { 
    
          if(aData[row][column] == null) 
          { 
           bw.append("null"); 
           // The comma separated value 
           bw.append(','); 
          } 
          else 
          { 
           /* In my particular example, I am doing some checking on 
    
            the 2d array for types: 
            if the data is not of type null (as checked above) 
            then it must be of type Integer. 
            This is because the 2D data array only contains data of either 
            Integer or null 
    
            each of these object types have a method called toString(). 
            we need this in order to convert the types to a string prior to wrting them to 
            the file. 
    
           */ 
           bw.append(aData[row][column].toString()); 
           bw.append(','); 
          } 
    
          }//end column loop (inner loop) 
    
          bw.append('\n'); 
    
         }//end row loop (outer loop) 
    
         bw.close(); 
    
        } 
        catch (Exception e) 
        { 
    
         e.getStackTrace(); 
        } 
    
        }//end of readFileFromDisk 
    
        /** 
        * 
        * These methods is responsible for printing the random sample scripts 
        * Into the command console. 
        * <p> 
        * 
        * 
        */ 
        public void printData() 
        { 
         //System.out.println(); 
         //System.out.println("=======WriteRandomSampleData Class==========="); 
         //System.out.println(); 
    
         for (int row = 0; row < data.length; row++) 
         { 
         for (int column = 0; column < data[row].length; column++) 
         { 
          System.out.println("data["+row+"]["+column+"] = " +data[row][column]); 
         } 
         } 
    
        } 
    
    //==================Instance Variables============================= 
        // JTable contents hedata 
        private Object[][] data; 
    
    //====================Test Driver============================ 
    
        public static void main(String args[]) 
        { 
        // file seperator for windows platform '\\' 
        String aFileLocation = "C:\\dirA\\subdir1\\subdir2\\"; 
    
        // Dummy values - 2D array which stores the contents of a 
        // JTable into a csv text file 
        Object[][] testData = new Object [][] { 
    
            {new Integer(1),new Integer(1),null,null,new Integer(11),new Integer(1),null,null}, 
            {new Integer(2),new Integer(1),null,null,new Integer(12),new Integer(1),null,null}, 
            {new Integer(3),new Integer(1),null,null,new Integer(13),new Integer(1),null,null}, 
            {new Integer(4),new Integer(1),null,null,new Integer(14),new Integer(1),null,null}, 
            {new Integer(5),new Integer(1),null,null,new Integer(15),new Integer(1),null,null}, 
            {new Integer(6),new Integer(1),null,null,new Integer(16),new Integer(1),null,null}, 
            {new Integer(7),new Integer(1),null,null,new Integer(17),new Integer(1),null,null}, 
            {new Integer(8),new Integer(1),null,null,new Integer(18),new Integer(1),null,null}, 
            {new Integer(9),new Integer(1),null,null,new Integer(19),new Integer(1),null,null}, 
            {new Integer(10),new Integer(1),null,null,new Integer(20),new Integer(1),null,null} 
    
            }; 
    // SampleData_TEST.csv gets created in the particular directory 
    // and the file gets populated with the contents of the JTable 
            new WriteRandomSampleData(testData,aFileLocation2+"SampleData_TEST.csv"); 
    
    
        } 
    } 
    

Le contenu du fichier SampleData_TEST.csv résultant sont décrits ci-dessous:

enter image description here

Comme décrit ci-dessus, le format de fichier .csv peut être ouvert dans Microsoft Excel qui peut être plus polyvalent (selon le type de données) qu'un fichier .doc ou .txt

Questions connexes