Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Why won't it read my Input file?

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    13
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question Why won't it read my Input file?

    I keep receiving an error in which State.Fall.txt can not be read. I can't point it directly to a drive because someone else needs to open it. I saved it in wordpad as a text file. My question is what did I do wrong in my code that it can't directly access the wordpad document?

     
     
    import java.io.*;
     
    public class Main {
     
        /**
         * @param args the command line arguments
         * 
         */
     
        public static void main(String[] args) throws IOException 
        {
            // Create an array of individual state objects to hold 50 items
            StateController myStateController;
            myStateController = new StateController(50);
     
            //call method to retrieve data and store in new array
            myStateController.loadData("States.Fall2014.txt");
     
            // display original array of states with headers
            myStateController.displayStates();
     
                // use bubble sort for state objects
                 myStateController.bubblesort();
     
                 myStateController.getCount();
     
                // contains search keys from file search
            myStateController.loadSearchKeys("State.Trans.txt");
     
              // Use binary search for alternate way to show results
                myStateController.binarySearch();
     
        }
     
        public Main() {
        }
     
    }// end Class Main


    public class State {
     
        private String stateName;
        private String stateCapital;
        private String stateAbbrev;
        private String stateRegion;
        private int statePopulation;
        private int regionNumber;
     
        /** 
        * @param name the name of the state
        * @param capital the capital of the state
        * @param abbrev the state's abbreviation
        * @param pop the population of the state
        * @param region the region of the state
        * @param regNum the region number of the state
        */
     
       public State (String name, String capital, String abbrev, String region,int pop, int regNum) 
        {
            stateName = name;
            stateCapital = capital;
            stateAbbrev = abbrev;
            stateRegion = region;
            statePopulation = pop;
            regionNumber = regNum;
     
        }//End State
     
       // Create getters for the six attributes
     
         /**
         * Returns the name of the state
         * @param None
         * @return stateName
         */
            public String getstateName()
            {
                return stateName;
            }
     
         /**
         * Returns state capital
         * @param None
         * @return stateCapital
         */
            public String getstateCapital()
            {
                return stateCapital;
            }
     
         /**
         * Returns state abbreviation
         * @param None
         * @return stateAbbrev
         */
            public String getstateAbbrev()
            {
                return stateAbbrev;
            }
     
     
         /**
         * Returns state region
         * @param None
         * @return stateRegion
         */
            public String getstateRegion()
            {
                return stateRegion;
            }
     
     
         /**
         * Returns region number
         * @param None
         * @return regionNumber
         */    
             public int getregionNumber()
            {
                return regionNumber;
            }
     
         /**
         * Returns statePopulation
         * @param None
         * @return statePopulation
         */     
            public int getstatePopulation()
            {
                return statePopulation;
            }
     
     
        /**
         * Data needed for the column headers
         * @return string
         */ 
        public String toString()
        {
            String str = String.format("%15s-%15s-%5s-%10s-%20s-%5s",
                stateName,stateCapital,stateAbbrev,stateRegion,regionNumber,statePopulation);
            return str;
        }//end toString
    }// end State class

     
     
     
    /**
     * Create class for state controller
     */
    public class StateController 
    {
        private State [] myStates;
        private int numStates = 0;
        private String[] searchKey = new String[14];
        private int numKeys;
        public int numSwap;   
     
     
     
    /**
     * Creates the Controller and array of state objects
     * @param maxSize 
     */
     
        public StateController(int maxSize)
        {
     
            myStates = new State[maxSize];
     
        }//end StateController
     
        public void loadData(String filename) throws IOException
        {
           FileInputStream fis1 = new FileInputStream("State.Fall2014.txt");
           BufferedReader br1 = new BufferedReader (new InputStreamReader(fis1));
           String name,capital,abbrev,region;
           int pop,regNum;  
     
           String inputString;
           inputString = br1.readLine();
     
           System.out.printf("%15s-%15s-%5s-%10s-%20s-%5s","Name","Capital","Abbrev",
                   "Population","Region","Region Number");
           System.out.println("==================================================================================================");
     
           while (inputString != null)
           {
               name = inputString.substring(0, 15).trim();
               capital=inputString.substring(15, 30).trim();
               abbrev=inputString.substring(30, 32).trim();
               region=inputString.substring(40, 55).trim();
               pop = Integer.parseInt(inputString.substring(32,40).trim());
               regNum = Integer.parseInt(inputString.substring(55,56).trim());
     
               myStates[numStates] = new State (name, capital, abbrev, region,pop, regNum);
               numStates++;
               inputString = br1.readLine();
           }
            br1.close();
        }
     
        public void displayStates()
        {
            int index;
            for(index = 0; index < numStates; index++)
            {
            System.out.println(myStates[index]);
        }//end for
    }//end displayStates
     
        public void bubbleSort()
        {
            int out,in;
            numSwap = 0;
            { 
            for (out = numStates - 1; out>1; out--)
                 for (in = 0; in<out; in++)
                 {
                     if (myStates[in].getStateName().compareTo(myStates[in +1].getStateName()) < 0)
                         swap (in, in +1);
                 }// end if(swap)
     
     
        }//end inner for loop
     
     
            System.out.println("Array of State Objects Sorted with A Bubble Sort");
            System.out.printf("%15s-%15s-%5s-%10s-%20s-%5s","Name","Capital","Abbrev",
                   "Population","Region","Region Number");
            System.out.println("==================================================================================================");
           displayStates();
        }//end bubble sort
     
        /**
         * //swap method to carry out the swap
         * @param one
         * @param two 
         */
        private void swap (int one, int two)
        {
            State name = myStates[one];
            myStates[one] = myStates[two];
            myStates[two] = name;
     
        }// end swap(int one, int two)
     
        public void getCount()
        {
            System.out.println("Number of swaps Using the Bubble sort on the Array of State Objects was: "+numSwap);
        }//end getCount()
     
        /**
         * reads input file
         * @param filename
         * @throws IOException 
         */
        public void loadSearchKeys(String filename) throws IOException
        {
            FileInputStream fis1 = new FileInputStream("State.Trans.txt");
            BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1));
            int end;
            String key;
     
            String inputString;
            inputString = br1.readLine();
     
            while(inputString !=null)
            {
                end = Math.min(14, inputString.length());
                key = inputString.substring(0,end);
               searchKey[numKeys] = key;
               numKeys++;
               inputString = br1.readLine();
     
            }//end while
            br1.close();
        }//end load searchkeys
     
        /**
         * displays result from search keys
         */
        public void displayKeys()
        {
            for(int index = 0; index < numKeys; index++)
            {
                System.out.println(searchKey[index]);
            }//end for        
        }//end display keys
     
        /**
         * Create a sequential search that uses "State.Trans.txt" file
         * @param searchKey
         * @return 
         */
      public String seqSearch(String searchKey) {
            int probe;
            String answer;
     
            for (probe = 0; probe < numStates; probe++) //for each object in array
            {
                if (myStates[probe].getName().compareToIgnoreCase(searchKey) == 0) //if found searchKey
                {
                    probe++;
                    break;                    //exit before end of loop
                }//end if
            }//end for
            if (probe == numStates) //searched all array elements?
            {
                probe++;
                answer = ("            X    ");      //if yes, can't find
            }//end if
            else {
                probe++;
                answer = ("  X              ");          //if no, found searchKey
            }//end else
     
            String format = "%1$-15s %2$-20s %3$6d"; //to align under column headers
            String result = String.format(format, searchKey, answer, probe);
            //format result
     
            return result;
     
      }//end sequential search
     
      /**
       * Create Binary search
       * @param searchKey
       * @return 
       */
     
      public String binarySearch(String searchKey) {
            int curIn;
            int probe = 0, lowerBound = 0, upperBound = numStates - 1;
            String format = "%1$-15s %2$-20s %3$6d";
            //to align results under column headers
            String answer, result;
     
            while (true) {
                curIn = (lowerBound + upperBound) / 2;//set curIn to middle of array
     
                if (myStates[curIn].getName().compareToIgnoreCase(searchKey) == 0) //found searchKey?
                {
                    probe++;
                    answer = ("  X              ");
                    result = String.format(format, searchKey, answer, probe);
                    //format search results
                    return result;
                }//end if
                else if (lowerBound > upperBound)//max probes reached?
                {
                    answer = ("            X    ");//can't find
                    result = String.format(format, searchKey, answer, probe);
                    //format search results
                    return result;
                }//end else if
                else {
                    probe++;
                    if (myStates[curIn].getName().compareToIgnoreCase(searchKey) < 0) //does curIn come before searchKey?
                    {
                        lowerBound = curIn + 1;//check upper half
                    }//end if 
                    else {
                        upperBound = curIn - 1;//check lower half
                    }//end else
                }//end else
            }//end while
        }//end binarySearch()
    }//end state controller


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Why won't it read my Input file?

    Probably because the code can't find the file.

    What in the heck does this mean:
    I can't point it directly to a drive because someone else needs to open it.
    Post the entire error message, copied from exactly as it appears at your end.

  3. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    13
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Why won't it read my Input file?

    The error codes won't match because I have still been working on my code but the error message has been the same... I am using Netbeans if that makes any difference. I have tried different things like changing the file or the packages but its still not working..





    Exception in thread "main" java.io.FileNotFoundException: States.Fall2014.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.jav a:131)
    at java.io.FileInputStream.<init>(FileInputStream.jav a:87)
    at program1.StateController.loadData(StateController. java:22)
    at main.Main.main(Main.java:14)

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Why won't it read my Input file?

    Explain the part about not being able to point to the file directly (or correctly). Why not? And what do you mean by "directly"? What are the requirements that prevent coding the path to the file? While you ponder that, you might also review the Class.getResource() method, but I'm not sure that's what will help you.

  5. #5
    Junior Member
    Join Date
    Jun 2014
    Posts
    13
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Why won't it read my Input file?

    I thought it was a matter of where I saved it which is on my flash drive. I just read somewhere that you would need to put e:/ filename. But I don't think that is really the case? It just needs to be in the same folder which I did but the program still does not "see it" . So I don't know if its something directly wrong in my code or that I still need to keep switching around where the file is located.

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Why won't it read my Input file?

    It doesn't matter where the file is, but the code needs to be able to find it and have access to it. This can be accomplished via a relative path or an absolute path. It's not magic, the code doesn't see what's in your head or everything attached to your computer. It needs a path.

  7. #7
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Why won't it read my Input file?

    You could use a JFileChooser and allow user to locate the file.
    Improving the world one idiot at a time!

Similar Threads

  1. [SOLVED] Program won't go to result after input. Help ASAP please..
    By Elyril in forum What's Wrong With My Code?
    Replies: 7
    Last Post: February 20th, 2014, 12:46 AM
  2. Trying to input a text file but the program won't read it.
    By Spanky_10 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 27th, 2013, 11:50 AM
  3. Why won't it read file?
    By tai8 in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: May 6th, 2012, 10:42 AM
  4. convert excel to xml and read the input from xml file
    By rahulruns in forum Object Oriented Programming
    Replies: 5
    Last Post: April 3rd, 2012, 11:13 AM
  5. Read input, read file, find match, and output... URGENT HELP!
    By MooseHead in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 3rd, 2012, 11:01 AM