有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。扫描仪如何在Java中使用扫描仪读取文本文件?

这是我读取文本文件的代码。当我运行这段代码时,输出总是说“找不到文件”,这是FileNotFoundException的消息。我不确定这段代码有什么问题

显然,这是java的一部分。对于整个java文件,它要求用户输入一些东西,并将使用输入作为名称创建一个文本文件。 之后,用户应再次输入之前创建的文本文件的名称(假设用户输入正确),然后程序应读取文本文件。 我已经正确地完成了程序的其他部分,但问题是当我再次输入名称时,它就是找不到文本文件,即使它们位于同一文件夹中

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

共 (6) 个答案

  1. # 1 楼答案

    还有一件事。。。使用System.err.println("Error Message Here")代替System.out.println("Error Message Here")。这将允许您通过以红色显示错误(即System.err.println()内的所有内容),来区分错误和正常代码功能之间的差异

    注意:与^{一起使用时也有效

  2. # 2 楼答案

    如果您在Eclipse或NetBeans之类的IDE中工作,那么在项目的根目录中应该有a.txt文件。(不在构建.class文件的文件夹或其他任何地方)

    如果没有,则应指定该文件的绝对路径


    编辑:
    如果用javac手动编译.txt文件,则可以将.txt文件与.class(通常也是.java文件,因为您在同一文件夹中编译)编译文件放在同一位置。这是因为它使用相对路径,该路径告诉JVM可执行文件所在的路径

    如果使用一些IDE,它将使用Mag文件或类似于Windows的类似文件为您生成编译的文件,并将其视为默认文件结构,因此他知道相对路径从项目的根文件夹开始。

  3. # 3 楼答案

    这应该能帮助你

    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!");
        }
    }
    
    }
    
  4. # 4 楼答案

    如果你给一个扫描器对象一个字符串,它会把它作为数据读入。也就是说,“a.txt”不会打开名为“a.txt”的文件。它的字面意思是‘a’,‘a’,‘a’等等

    这是根据核心Java第一卷第3.7.3节

    如果我找到了读取实际路径的解决方案,我将返回并更新此答案。本文提供的解决方案是使用

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

    但我无法实现这一点,因为编译器无法将Path识别为变量。也许我错过了一个重要的声明

  5. # 5 楼答案

    嗯。。显然,该文件不存在或找不到。尝试使用完整路径。如果不指定路径,则可能是从错误的目录中读取,除非a.txt在当前工作目录中

  6. # 6 楼答案

    我建议将文件作为资源加载,并将输入流转换为字符串。这将使您能够灵活地将文件加载到相对于类路径的任何位置