how to read a text file using scanner in Java?

走远了吗. 提交于 2019-12-05 19:41:21

问题


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;
    }

回答1:


Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.




回答2:


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.




回答3:


I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath




回答4:


If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.

This is according to Core Java Volume I, section 3.7.3.

If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use

Scanner in = new Scanner(Paths.get("myfile.txt"));

But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.




回答5:


This should help you..:

import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
    find(Recipe);
}
public void find(String Name){
    String newRecipe= Name+".txt";
    try{
        FileReader fr= new FileReader(newRecipe);
        BufferedReader br= new BufferedReader(fr);

        String str;


    while ((str=br.readLine()) != null){
            out.println(str + "\n");
        }
        br.close();

    }catch (IOException e){
        out.println("File Not Found!");
    }
}

}



回答6:


Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.

NOTE: It also works when used with System.err.print("Error Message Here")



来源:https://stackoverflow.com/questions/6082586/how-to-read-a-text-file-using-scanner-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!