11 Replies Latest reply: Dec 13, 2006 12:51 AM by 807599 RSS

    Please help : Problem with reading and manipulating data from a txt file..

    807599
      Hi
      Can i read data from a file and do manipulations on it..

      I have a text file named name.txt which contains names in random order
      :
      Shaun
      David
      Peter
      Sean
      Andrew


      Now how to Print them on the console in alphabetical order :

      Andrew
      David
      Peter
      Sean
      Shaun


      I am able to read the Input from a file and display it on the console but how to Print them alphabetically

      import java.io.*;
      
      public class TestFileReader
      {
          public static void main(String[] args)
          {
              // TODO Auto-generated method stub
              try
              {
                  File file = new File("D:\\Name.txt");
                  FileReader f = new FileReader(file);
                  int ch;
                  while((ch=f.read())!=-1)
                  {
                      System.out.print((char)ch);
                  }
                  
              }
              catch(FileNotFoundException fnfe)
              {
                  System.out.println("Exception : " +fnfe.toString());
              }
              catch(IOException ioe)
              {
                  System.out.println("Exception : " + ioe.toString());
              }
          }
      
      }
      ....
      ******
      I created a another program which reads the data given in the program and print them in alphabetical order...
      import java.util.*;
      
      public class Name
      {
          public static void main(String[] args)
          {
              String names[] = { "Shaun","David","Peter","Sean","Andrew" };
              System.out.println("The original order:");
              for (int i = 0; i < names.length; i++)
                  System.out.println(names);
      Arrays.sort(names);

      System.out.println();
      System.out.println("The new order:");
      for (int i = 0; i < names.length; i++)
      System.out.println(names[i]);
      }
      }

      Out Put
      Andrew
      David
      Peter
      Sean
      Shaun



      Please help...
      Thank you...
        • 1. Re: Please help : Problem with reading and manipulating data from a txt fil
          807599
          Consider using a BufferedReader rather than a (plain) FileReader. It has a
          readLine() method that reads a whole line (name) at a time. This will enable
          you to read each name as a single unit rather than a sequence of characters
          as you are doing at the moment.

          BufferedReader is documented here:
          http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html
          And there is an example of its usage here:
          http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html

          Once you have "stored" each name to an element of an array you
          should be well placed to be able to sort the array. (This isn't meant to
          suggest that there might not be better data structures to use like an ArrayList,
          but a plain array of Strings is doable.)
          • 2. Re: Please help : Problem with reading and manipulating data from a txt file..
            807599
            use BufferedReader to read your file Line by line, save them in Array
            and sorty them the same way you did in second programm
            • 3. Re: Please help : Problem with reading and manipulating data from a txt fil
              807599
              > BufferedReader is documented here:
              http://java.sun.com/j2se/1.5.0/docs/api/java/io/Buffer
              edReader.html
              And there is an example of its usage here:
              http://www.exampledepot.com/egs/java.io/ReadLinesFromF
              ile.html

              Once you have "stored" each name to an element of an
              array you

              Thanks got the logic but... how to put them in an array...?

              and the example i saw from the latter link which you had sent what is process in that.. its a method but what should that method contain?

              Message was edited by:
              New_to_Java
              • 4. Re: Please help : Problem with reading and manipulating data from a txt fil
                807599
                Thanks got the logic but... how to put them in an array...?

                and the example i saw from the latter link which you had sent what is process
                in that.. its a method but what should that method contain?
                They use process() as a sort of placeholder for whatever you want to do ... In
                your case this is putting the strings into an array. So it will look like:
                public static void main(String[] args)
                {
                    String[] names = // create a big enough array here
                                     // initially it is full of nulls
                
                    int ndx = 0;
                    try {
                    BufferedReader in = new BufferedReader(new FileReader("D:\\Name.txt"));
                        String str;
                        while ((str = in.readLine()) != null) {
                                // These two lines are "process"
                            names[ndx] = str;
                            ndx++;
                        }
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // System.exit(1);
                    }
                
                    // now you can sort
                }
                To do the sort you will have to use the other form of Arrays.sort() - the
                one that takes a fromIndex and a toIndex. Do you see why?
                • 5. Re: Please help : Problem with reading and manipulating data from a txt fil
                  807599
                  Hi :
                  Sorry my internet was down...
                  But When i am doing the way you have told I am able to print the names from the file into String array but after Printing the names the out is this
                  Out Put
                  Andrew
                  David
                  Peter
                  Sean
                  Shaun

                  Exception in thread "main" java.lang.NullPointerException
                       at java.util.Arrays.mergeSort(Unknown Source)
                       at java.util.Arrays.mergeSort(Unknown Source)
                       at java.util.Arrays.mergeSort(Unknown Source)
                       at java.util.Arrays.mergeSort(Unknown Source)
                       at java.util.Arrays.mergeSort(Unknown Source)
                       at java.util.Arrays.sort(Unknown Source)
                       at NameTrial.main(NameTrial.java:36)



                  The Code I used Am sending please tell me how to rectify it..
                  import java.io.*;
                  import java.util.*;
                  
                  public class NameTrial
                  {
                      static int ndx = 0;
                      static String[] names = new String[100];
                      static String str;
                  
                      // TODO Auto-generated method stub
                      public static void main(String[] args)
                      {
                  
                          try
                          {
                              BufferedReader in = new BufferedReader(new FileReader(
                                  "D:\\Name.txt"));
                  
                              while ((str = in.readLine()) != null)
                              {
                                  names[ndx] = str;
                                  ndx++;
                              }
                              in.close();
                              for (int j = 0; j < ndx; j++)
                              {
                                  System.out.println(names[j]);
                              }
                           
                          }
                          catch (IOException e)
                          {
                              e.printStackTrace();
                          }
                  
                          Arrays.sort(names);
                  
                          System.out.println();
                          System.out.println("The Out put after Sorting alphabetically:");
                          for (int i = 0; i < names.length; i++)
                              System.out.println(names);

                  }
                  }



                  Am i using the sorting block at the right place..????
                  • 6. Re: Please help : Problem with reading and manipulating data from a txt fil
                    807599
                    You didnt listen to the advice that was given to you.

                    What happens when you send names to Arrays.sort?

                    Well, it trys to sort the array you gave it from index 0 to the arrays length-1.

                    This would be fine and dandy if your array was teh exact length of the number of elements you stored, but that isnt the case is it?

                    Your array's length is 100, but your array isnt necesarily going to be that long is it? Which is why you get a NullPointerException. This means that the sorting algorithm tried to do comparisons on a null object. When you sent your array to the sort method, the majority of your array was null.

                    This is why you need to use the Arrays.sort(array, int startIndex, int endIndex) version of it. Can you see why now? What would be your endIndex?
                    • 7. Re: Please help : Problem with reading and manipulating data from a txt fil
                      807599
                      This is why you need to use the Arrays.sort(array, int startIndex, int endIndex)
                      version of it.
                      For the same reason you will have to be careful when you print out the sorted
                      array.

                      But, yes, you are sorting in the right place.
                      • 8. Re: Please help : Problem with reading and manipulating data from a txt fil
                        807599
                        Use ArrayList, instead of array
                        import java.io.BufferedReader;
                        import java.io.FileReader;
                        import java.util.ArrayList;
                        import java.util.Collections;
                        
                        public class SortFile {
                        
                             public static void main(String[] args) {
                        
                                  try {
                                       BufferedReader br = new BufferedReader(new FileReader("C:\\input.txt"));
                                       String str = null;
                                       ArrayList al = new ArrayList();
                        
                                       while ((str = br.readLine()) != null) {
                                            al.add(str);
                                       }
                                       br.close();
                                       
                                       Collections.sort(al);
                                       
                                       System.out.print(al);
                                  } 
                                  catch (Exception e) {
                                       e.printStackTrace();
                                  }
                             }
                        }
                        Cheers
                        • 9. Re: Please help : Problem with reading and manipulating data from a txt fil
                          807599
                          This is why you need to use the Arrays.sort(array,
                          int startIndex, int endIndex)
                          version of it.
                          For the same reason you will have to be careful when
                          you print out the sorted
                          array.

                          But, yes, you are sorting in the right place.
                          Thanks a lot its working but still null is getting printed... what should i put instead of 100..
                          or do i need to change something
                          in
                           static String[] names;// = new String[100];
                          • 10. Re: Please help : Problem with reading and manipulating data from a txt fil
                            807599
                            thanks alot .. got it ..
                            i realized ... in the for loop below....it should be j instead of names.length
                            Arrays.sort(names, 0, j); 
                                    System.out.println();
                                    System.out.println("The new order:");
                                    for (int i = 0; i < j; i++) // it should be j instead of  names.length
                                        System.out.println(names);


                            Thanks a lot.. i am getting it right now...

                            Message was edited by:
                            New_to_Java
                            • 11. Re: Please help : Problem with reading and manipulating data from a txt fil
                              807599
                              it should be j instead of names.length
                              Exactly.
                              Thanks a lot.. i am getting it right now...
                              You're welcome.