13 Replies Latest reply on May 10, 2009 11:48 PM by camickr

    sorting alphabetically .txt files

    807588
      hi, i have a text file full of info and i need to sort the NAT column alphabetically e.g of info:
      Name         Age Prs Nat St Tk Ps Sh Ag KAb TAb PAb SAb Gam Sub  Min Mom Sav Con Ktk Kps Sht Gls Ass  DP Inj Sus
      ----------------------------------------------------------------------------------------------------------------
      B.Friedel     38 LRC usa 20  1  1  1 21 410 300 300 300  18   0 1673   0  76  26   0   0   0   0   0   0   0   0
      M.Fulop       26 LRC hun 17  1  1  1 26 308 300 300 300   1   1   16   0   1   0   0   0   0   0   0   0   0   0
      B.Guzan       25 LRC usa 15  1  1  1 23 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
      M.Laursen     32   C den  1 24  6 12 25 300 493 409 373  17   0 1619   0   0   0  17   7  15   2   0  14   0   0
      C.Davies      24   C eng  1 23  9  6 25 300 302 430 304  15   0 1457   0   0   0   8   9   6   0   0   4   0   0
      C.Cuellar     28  RC esp  1 23 12  8 24 300 302 412 320  14   1 1273   0   0   0  10  10  13   0   0   8   0   0
      L.Young       30  RC eng  1 23 10  6 22 280 328 435 316  11   1 1006   0   0   2  14   9   5   0   0   0   0   0
      what would i need to do to sort only the Nat column? but everything else ajdusts with it..
      oh and i also need it to remain displayed this way when it is sorted.

      can someone point me in the right direction please :)

      Edited by: bokz06 on May 9, 2009 9:20 PM
        • 1. Re: sorting alphabetically .txt files
          793415
          >
          ...
          what would i need to do to sort only the Nat column? but everything else ajdusts with it..>
          I do not understand. If you sorted the NAT column alphabetically, why would you not want the other columns to adjust with it? If they did not adjust with it, the 'sorted table' would imply that B. Friedel was from Denmark, and L. Young was from the USA.

          Are you using a JTable? I think I'd need to see an SSCCE to understand what your were doing (though I make no guarantees that an SSCCE will answer those questions).
          • 2. Re: sorting alphabetically .txt files
            807588
            yeah i need the other columns to adjust with it, your right.... i just dont know where to start? what would i need to do? i need help with a starting point.
            • 3. Re: sorting alphabetically .txt files
              DrClap
              Okay, here's your starting point:

              Read each line of the text file into an object of a class which you design specifically for this purpose, and add each object to a List of such objects.

              Then sort the List. Done.

              Make sure that the class you design implements Comparable, so you can actually sort the objects. Or if you might need to sort on several columns, write a Comparator for each column and pass that to the sort method of the List.
              • 4. Re: sorting alphabetically .txt files
                807588
                i have no clue how to do what your saying.. i am very new to java, is there no other more simple/"stupid" way of doing it?

                oh and my text will be much longer then the example i gave here... like 500 lines or more..
                • 5. Re: sorting alphabetically .txt files
                  793415
                  >
                  ...i need help with a starting point.>
                  Start with 'reading the file'.

                  The problem with such a vague question is that there are a large number of ways to read the File, then do the further actions needed to sort the list. The best way might depend on other factors not yet mentioned, for example. Is it necessary to persist (save) the reordered file, or is all this re-ordering of rows done only at run-time?

                  But a couple of strategies to consider..
                  For reading and parsing the data from text, I might try one of two methods.
                  1) Establish a LineReader pointing to the file, read each line into a Vector (or ArrayList) or String[], then iterate the lines and then..
                  String[] rowFields = line.split(" "); //split the line using space character as delimiter.
                  2) Using a Scanner pointing to the File. A Scanner is better suited to parsing the fields, but I have not used them much.

                  For displaying the data, and reordering it at run-time, I would recommend a JTable (a natural choice for tabular data!) and use the TableRowSorter (Java 1.6+) to sort the data any which way the user wants.
                  • 6. Re: sorting alphabetically .txt files
                    DrClap
                    I don't like telling people stupid ways of doing things. And why would you think it makes any difference how many rows there are?

                    So do yourself a favour and read the [Java Collections Tutorial|http://java.sun.com/docs/books/tutorial/collections/index.html]. It's all in there. Don't spend any time building a bunch of arrays and writing bubble-sort code to sort them.
                    • 7. Re: sorting alphabetically .txt files
                      YoungWinston
                      bokz06 wrote:
                      hi, i have a text file full of info and i need to sort the NAT column alphabetically e.g of info:
                      Name         Age Prs Nat St Tk Ps Sh Ag KAb TAb PAb SAb Gam Sub  Min Mom Sav Con Ktk Kps Sht Gls Ass  DP Inj Sus
                      ----------------------------------------------------------------------------------------------------------------
                      B.Friedel     38 LRC usa 20  1  1  1 21 410 300 300 300  18   0 1673   0  76  26   0   0   0   0   0   0   0   0
                      M.Fulop       26 LRC hun 17  1  1  1 26 308 300 300 300   1   1   16   0   1   0   0   0   0   0   0   0   0   0
                      B.Guzan       25 LRC usa 15  1  1  1 23 300 300 300 300   0   0    0   0   0   0   0   0   0   0   0   0   0   0
                      M.Laursen     32   C den  1 24  6 12 25 300 493 409 373  17   0 1619   0   0   0  17   7  15   2   0  14   0   0
                      C.Davies      24   C eng  1 23  9  6 25 300 302 430 304  15   0 1457   0   0   0   8   9   6   0   0   4   0   0
                      C.Cuellar     28  RC esp  1 23 12  8 24 300 302 412 320  14   1 1273   0   0   0  10  10  13   0   0   8   0   0
                      L.Young       30  RC eng  1 23 10  6 22 280 328 435 316  11   1 1006   0   0   2  14   9   5   0   0   0   0   0
                      what would i need to do to sort only the Nat column? but everything else ajdusts with it..
                      oh and i also need it to remain displayed this way when it is sorted.

                      can someone point me in the right direction please :)

                      Edited by: bokz06 on May 9, 2009 9:20 PM
                      As others have suggested, you need to read the java tutorials or indeed the API documentation.
                      For reading in the file, you'll need to look at the ...InputStream and ...Reader classes; and for sorting the lines it'll save you a lot of coding if you get familiar with the Java collections framework. I suspect you'll want some kind of Map, but there are lots of alternatives.

                      Winston
                      • 8. Re: sorting alphabetically .txt files
                        807588
                        ok this is what i have so far, i get the arraylist to display in the terminal but i dont think the Split() method is working, i get a null error and my output is still the same as the original. what am i doing wrong with the split? someone please help
                        import java.io.BufferedReader;
                        import java.io.FileNotFoundException;
                        import java.io.FileReader;
                        import java.io.IOException;
                        import java.util.*;
                        
                        
                        public class rosterSorter
                        {
                        public static void main() 
                          {
                             BufferedReader br = null;
                             ArrayList rosterList = new ArrayList();
                             
                             try
                            {
                              br = new BufferedReader(new FileReader("mydata.txt"));
                              String line = br.readLine();
                              while (line != null )
                              {
                                String [] rowfields = line.split(" ");  
                                line = br.readLine();
                                rosterList.add(line);
                                
                                      
                              }
                              
                            }
                            catch (FileNotFoundException e)
                            {
                              // can be thrown when creating the FileReader/BufferedReader
                              // deal with the exception
                              e.printStackTrace();
                            }
                            catch (IOException e)
                            {
                              // can be thrown by br.readLine()
                              // deal with the exception
                              e.printStackTrace();
                            }
                            show(rosterList);
                            
                        }
                            public static void show(ArrayList rosterList){
                                
                            for (int i = 0; i < rosterList.size(); i++)
                            {
                                System.out.println(rosterList.get(i));
                            }
                        }
                          
                            
                        }
                        • 9. Re: sorting alphabetically .txt files
                          YoungWinston
                          bokz06 wrote:
                          ok this is what i have so far, i get the arraylist to display in the terminal but i dont think the .split method is working, i get a null error and my output is still the same as the original. what am i doing wrong with the split? someone please help
                          Seems to me that it's probably working just fine; you're just not using the results. Where do you reference 'rowfields'? I suspect you can't, as it's defined inside your 'while' loop.
                          Think it through as bit more: Why do you want to split the line? How do you intend to use the result? Where do you intend to sort your lines, and how are you going to do it or, better still (hint), have a Java class do it for you?

                          Good hunting

                          Winston
                          • 10. Re: sorting alphabetically .txt files
                            YoungWinston
                            bokz06 wrote:
                            in the mydata.txt file:
                            B.Friedel     38 LRC usa 20  1  1  1 21 410 300 300 300  18   0 1673   0  76  26   0   0   0   0   0   0   0   0
                            M.Fulop       26 LRC hun 17  1  1  1 26 308 300 300 300   1   1   16   0   1   0   0   0   0   0   0   0   0   0
                            ...
                            One other thing: the split() method, as you've written it, splits specifically on a single space. How many spaces are there between 'Friedel' and '38' in the first line of your file?
                            If you look at the method declaration in the API, you'll notice that it takes a string called 'regex'. This indicates that the string is a 'regular expression' (yet another thing to learn about :-)).
                            As you may not have covered this one yet, I'll give you this for free: you'll be better off using
                            "[ ]+"
                            as your split() string. This says, 'split the string on any occurence of 1 or more spaces'.

                            Keep plugging away. You'll get there.
                            • 11. Re: sorting alphabetically .txt files
                              807588
                              thanks mate, i was wondering why it wasnt splitting correctly... ahah
                              • 12. Re: sorting alphabetically .txt files
                                807588
                                import javax.swing.JFrame;
                                import javax.swing.JPanel;
                                import javax.swing.JScrollPane;
                                import javax.swing.JTable;
                                import javax.swing.table.AbstractTableModel;
                                import java.awt.Dimension;
                                import java.awt.GridLayout;
                                import java.io.*;
                                import java.util.*;
                                
                                
                                public class TableDemo extends JPanel {
                                    private boolean DEBUG = false;
                                    ArrayList rosterList = new ArrayList();
                                
                                    public TableDemo() {
                                        super(new GridLayout(1,0));
                                
                                        JTable table = new JTable(new MyTableModel());
                                        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                                        table.setFillsViewportHeight(true);
                                
                                        //Create the scroll pane and add the table to it.
                                        JScrollPane scrollPane = new JScrollPane(table);
                                
                                        //Add the scroll pane to this panel.
                                        add(scrollPane);
                                    }
                                
                                    class MyTableModel extends AbstractTableModel {
                                        private String[] columnNames = { "Name", "Age", "Pos", "Nat", "St", "Tk", "Ps", "Sh", "Ag", "Kab", "Tab", "Pab", "Sab", "Gam", "Sub", "Min", "Mom", "Sav", "Con", "Ktk", "Kps", "Sht", "Gls", "Ass", "DP", "Inj", "Sus"};
                                        
                                
                                        public int getColumnCount() {
                                            return columnNames.length;
                                        }
                                
                                        public int getRowCount() {
                                            return rosterList.size();
                                        }
                                
                                        public String getColumnName(int col) {
                                            return columnNames[col];
                                        }
                                
                                      
                                        public Object getValueAt(int row, int col) 
                                        {    
                                            return rosterList.at(row)[col];   *<-------- Error Here says: cannot find symbol  method at(int)*
                                        }
                                
                                        
                                    }
                                
                                   
                                    private static void createAndShowGUI() {
                                        //Create and set up the window.
                                        JFrame frame = new JFrame("TableDemo");
                                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                
                                        //Create and set up the content pane.
                                        TableDemo newContentPane = new TableDemo();
                                        newContentPane.setOpaque(true); //content panes must be opaque
                                        frame.setContentPane(newContentPane);
                                
                                        //Display the window.
                                        frame.pack();
                                        frame.setVisible(true);
                                    }
                                
                                    public static void main(String[] args) {
                                        //Schedule a job for the event-dispatching thread:
                                        //creating and showing this application's GUI.
                                        javax.swing.SwingUtilities.invokeLater(new Runnable() {
                                            public void run() {
                                                creatArr();
                                                createAndShowGUI();
                                            }
                                        });
                                    }
                                    
                                
                                private static void creatArr() 
                                  {
                                     BufferedReader br = null;
                                     
                                     try
                                    {
                                      br = new BufferedReader(new FileReader("mydata.txt"));
                                      String line = br.readLine();
                                        
                                      while (line != null )
                                      {
                                        String [] rowfields = line.split("[ ]+");
                                        rosterList.add(rowfields);    *<--------------------- Error here says: non static variable rosterList cannot be referenced from a Static context*
                                        line = br.readLine();
                                       }
                                     
                                    }
                                    catch (FileNotFoundException e)
                                    {
                                      // can be thrown when creating the FileReader/BufferedReader
                                      // deal with the exception
                                      e.printStackTrace();
                                    }
                                    catch (IOException e)
                                    {
                                      // can be thrown by br.readLine()
                                      // deal with the exception
                                      e.printStackTrace();
                                    }
                                    
                                    
                                }
                                    
                                  
                                    
                                
                                }
                                • 13. Re: sorting alphabetically .txt files
                                  camickr
                                  creatArr();
                                  createAndShowGUI();
                                  The createArr() method should be part of the constructor code that create the table. So get rid of the static keyword.

                                  Also, I know the tutorial shows an example of creating a custom TableModel, but for your first table it is probably easier to just use the DefaultTableModel. So you start by creating an empty model. Then as you "split" each row of data you use the addRow(...) method of the DefaultTableModel to add new rows of data. Then when all the data is in the model you create the table using the model. So your code would be something like:
                                  String[] columnNames = ...
                                  DefaultTableModel model = new DefaultTableModel( columnNames );
                                  addDataToModel( model ); // rename your creatArr method
                                  JTable table = new JTable( model );