how to read a text file using scanner in Java?

user764073 picture user764073 · May 21, 2011 · Viewed 130.1k times · Source

This is my code to read a text file. When I run this code, the output keeps saying "File not found.", which is the message of FileNotFoundException. I'm not sure what is the problem in this code.

Apparently this is part of the java. For the whole java file, it requires the user to input something and will create a text file using the input as a name. After that the user should enter the name of the text file created before again (assume the user enters correctly) and then the program should read the text file. I have done other parts of my program correctly, but the problem is when i enter the name again, it just can not find the text file, eventhough they are in the same folder.

public static ArrayList<DogShop> readFile()
    {

        try 
        {   // The name of the file which we will read from
            String filename = "a.txt";

            // Prepare to read from the file, using a Scanner object
            File file = new File(filename);
            Scanner in = new Scanner(file);

            ArrayList<DogShop> shops = new ArrayList<DogShop>();

            // Read each line until end of file is reached
            while (in.hasNextLine())
            {
                // Read an entire line, which contains all the details for 1 account
                String line = in.nextLine();

                // Make a Scanner object to break up this line into parts
                Scanner lineBreaker = new Scanner(line);



                // 1st part is the account number
                try 
                {   int shopNumber = lineBreaker.nextInt();

                    // 2nd part is the full name of the owner of the account
                    String owner = lineBreaker.next();

                    // 3rd part is the amount of money, but this includes the dollar sign
                    String equityWithDollarSign = lineBreaker.next();

                    int total = lineBreaker.nextInt();

                    // Get rid of the dollar sign;
                    // we use the subtring method from the String class (see the Java API),
                    // which returns a new string with the first 'n' characters chopped off,
                    // where 'n' is the parameter that you give it
                    String equityWithoutDollarSign = equityWithDollarSign.substring(1);

                    // Convert this balance into a double, we need this because the deposit method
                    // in the Account class needs a double, not a String
                    double equity = Double.parseDouble(equityWithoutDollarSign);

                    // Create an Account belonging to the owner we found in the file
                    DogShop s = new DogShop(owner);



                    // Put money into the account according to the amount of money we found in the file
                    s.getMoney(equity);

                        s.getDogs(total);

                    // Put the Account into the ArrayList
                    shops.add(s);
                }

                catch (InputMismatchException e)
                {
                    System.out.println("File not found1.");

                }

                catch (NoSuchElementException e)
                {
                    System.out.println("File not found2");

                }

            }



        }


        catch (FileNotFoundException e)
        {
            System.out.println("File not found");

        }   // Make an ArrayList to store all the accounts we will make








        // Return the ArrayList containing all the accounts we made
        return shops;
    }

Answer

Iulius Curt picture Iulius Curt · May 21, 2011

If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)

If not, you should specify the absolute path to that file.


Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.

If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.