简体   繁体   English

如何使用Java中的扫描程序读取文本文件?

[英]how to read a text file using scanner in Java?

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 . 当我运行此代码时,输​​出会一直显示“File not found。”,这是FileNotFoundException的消息。 I'm not sure what is the problem in this code. 我不确定这段代码中的问题是什么。

Apparently this is part of the java. 显然这是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. 对于整个java文件,它要求用户输入内容并使用输入作为名称创建文本文件。 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;
    }

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. 除非a.txt在您当前的工作目录中,否则您可能在未指定路径时从错误的目录中读取。

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. 如果您在某些IDE(如Eclipse或NetBeans)中工作,则应该在项目的根目录中包含该a.txt文件。 (and not in the folder where your .class files are built or anywhere else) (而不是在构建.class文件的文件夹中或其他任何位置)

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 . 你可以将.txt文件与.class (通常也是.java文件,因为你在同一个文件夹中编译)编译文件放在同一个地方,如果你用javac手工编译它。 This is because it uses the relative path and the path tells the JVM the path where the executable file is located. 这是因为它使用相对路径,路径告诉JVM可执行文件所在的路径。

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. 如果您使用某些IDE,它将使用Makefile或类似的东西为您生成编译的文件,并将其视为默认文件结构,因此他知道相对路径从项目的根文件夹开始。

If you give a Scanner object a String, it will read it in as data. 如果为Scanner对象提供String,则会将其作为数据读入。 That is, "a.txt" does not open up a file called "a.txt". 也就是说,“a.txt”不会打开名为“a.txt”的文件。 It literally reads in the characters 'a', '.', 't' and so forth. 它字面上读取字符'a','。','t'等等。

This is according to Core Java Volume I, section 3.7.3. 这是根据Core Java第I卷第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. 但我不能让它工作,因为编译器不会将Path识别为变量。 Perhaps I'm missing an import statement. 也许我错过了一个导入声明。

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!");
    }
}

}

Just another thing... Instead of System.out.println("Error Message Here") , use System.err.println("Error Message Here") . 另一件事......使用System.err.println("Error Message Here") System.out.println("Error Message Here")而不是System.out.println("Error Message Here") System.err.println("Error Message Here") This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(ie everything inside System.err.println() ) in red. 这将允许您通过以红色显示错误(即System.err.println()内的所有内容System.err.println()来区分错误和正常代码功能之间的差异。

NOTE : It also works when used with System.err.print("Error Message Here") 注意 :它与System.err.print("Error Message Here")一起使用时也有效

I would recommend loading the file as Resource and converting the input stream into string. 我建议将文件加载为Resource并将输入流转换为字符串。 This would give you the flexibility to load the file anywhere relative to the classpath 这将使您可以灵活地将文件加载到相对于类路径的任何位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM